Making a space invaders knock off game. My code will not compile as I get the error message "It looks like you're mixing 'active' and 'static' modes", but I can not see where I am mixing them. Can someone please take a look at my code?
final int SCREENX=400;
final int SCREENY=400;
final int GAP=10;
final int ALIEN_ALIVE=0;
final int ALIEN_DEAD=6;
final int FORWARD=0;
final int BACKWARD=1;
final int MARGIN=30;
Alien theAliens[];
Bullet bullets[];
Player thePlayer;
void setup() {
PImage normalImg, explodeImg;
size(SCREENX, SCREENY);
normalImg =loadImage("invader.GIF");
explodeImg =loadImage("exploding.GIF");
theAliens = new Alien[10];
bullets = new Bullet[20];
init_aliens(theAliens, normalImg, explodeImg);
thePlayer = new Player(SCREENY- 50);
}
void init_aliens(Alien baddies[], PImage okImg, PImage
exImg) {
for (int i=0; i<baddies.length; i++) {
// This is buggy, what is the problem?
baddies[i] = new Alien(i*(okImg.width+GAP), 0, okImg,
exImg);
}
}
void init_bullets() {
for (int i = 0; i < bullets.size(); i++) {
Bullet b = (Bullet) bullets.get(i);
b.move();
b.draw();
}
}
void shoot() {
if (mousePressed)
Player.shoot();
}
void draw() {
background(0);
thePlayer.draw();
thePlayer.move(mouseX);
draw_bullets(myBullets);
for (int i=0; i<theAliens.length; i++) {
theAliens[i].move();
theAliens[i].draw();
if (random(0, 500)<1)
theAliens[i].die();
}
}
////// Player Class //////
Player() { ///** When I get the error, this line is highlighted**///
this.x = width/2;
this.y = height-50;
this.timeLastShot = 0;
this.coolDown = 200;
colour playColour= color(50);
void draw() {
fill(playerColour);
rect(this.x, this.y, 30, 30);
}
void move(int x) {
if (x>SCREENX-50)
xpos= SCREENX-50;
else xpos=x;
}
void shoot() {
if (millis() - timeLastShot > coolDown) {
Bullet bullet = new Bullet(this.x+12.5, this.y, -5);
bullets.add(bullet);
timeLastShot = millis();
}
}
}
Your Player class is badly written. It should be:
class Player {
Player () {
//constructor
}
void functionOfSorts () {
} // Never forget to enclose functions with curly brackets!
}
...As opposed to what you wrote:
Player() {
//yadayada
}
Related
I try to make a web application.
You can change cells of the array by pressing arrow keys here.
There is a class "Module" with methods display() and update(). These methods change the inner array data[].
class Module {
int i; // index
int x; // coordinate
int y; // coordinate
int[] data = new int[]{0,0,0,0,0};
// Contructor
Module(int x){
this.x = x;
}
void update() {
data[i]=_mas_stor;
}
void display(){
text(data[i], x, 100);
}
}
But how to set the initial value of the array _mass[] at the beginning of the program?
The whole program here.
There is no need of an array of data in the class Module. It is sufficient that each object has it single data member. Wirte a constructor, eher you can pass to the initial data (Module(int x, int d)):
class Module {
int i;
int x;
int y;
int data;
// Contructor
Module(int x, int d){
this.x = x;
this.data = d;
}
void update() {
data=_mas[global_i];
}
void display(){
textSize(30);
text(data, x, 100);
}
}
Now the object can be initialized in a loop with ease:
int[] _mas ={1,2,3,4,5};
int global_i = 0;
Module [] mods;
void setup() {
size(500, 400);
mods = new Module[5];
for (int i = 0; i < 5; ++ i ) {
mods[i] = new Module(i*50+50, _mas[i]);
}
}
Further you have to ensure that global_i doesn't go out of bounds in keyPressed:
void keyPressed() {
if (keyCode == UP) {
_mas[global_i]++;
}
if (keyCode == DOWN) {
_mas[global_i]--;
}
if (keyCode == LEFT) {
global_i--;
if (global_i < 0)
global_i = 4;
}
if (keyCode == RIGHT) {
global_i++;
if (global_i > 4)
global_i = 0;
}
}
Note, you can further improve you program, if you skip the global variable _mas and add a increment method (inc) and decrement method (dec) to the class Module, instead of the update method:
int global_i = 0;
Module [] mods;
void setup() {
size(500, 400);
mods = new Module[5];
for (int i = 0; i < 5; ++ i ) {
mods[i] = new Module(i*50+50, i);
}
}
void draw() {
background(50);
for (int i = 0; i < 5; ++ i ) {
mods[i].display();
}
}
void keyPressed() {
if (keyCode == UP) {
println("up");
mods[global_i].inc();
}
if (keyCode == DOWN) {
mods[global_i].dec();
}
if (keyCode == LEFT) {
global_i--;
if (global_i < 0)
global_i = 4;
}
if (keyCode == RIGHT) {
global_i++;
if (global_i > 4)
global_i = 0;
}
}
class Module {
int i;
int x;
int y;
int data;
// Contructor
Module(int x, int d){
this.x = x;
this.data = d;
}
void inc() {
this.data ++;
}
void dec() {
this.data --;
}
void display(){
textSize(30);
text(data, x, 100);
}
}
You usually set the initial value of an array using a for loop. Something like this:
String myArray = new String[10];
for(int i = 0; i < myArray.length; i++){
myArray[i] = "hello world";
}
What you put inside the for loop depends on what values you want your array to start with.
I am trying to make a simple top down shooter. When the user presses W, A, S or D a 'bullet' (rectangle) will come out of the 'shooter'. With my code, you can only shoot one bullet per direction until it reaches the end of the screen. Is there a way to make it so they (the user) can shoot multiple bullets in one direction?
Here's my code:
package topdownshooter;
import processing.core.PApplet;
import processing.core.PImage;
public class TopDownShooter extends PApplet {
PImage shooter;
float shooterX = 400;
float shooterY = 300;
float u_bulletSpeed;
float l_bulletSpeed;
float d_bulletSpeed;
float r_bulletSpeed;
boolean shootUp = false;
boolean shootLeft = false;
boolean shootDown = false;
boolean shootRight = false;
public static void main(String[] args) {
PApplet.main("topdownshooter.TopDownShooter");
}
public void setup() {
shooter = loadImage("shooter.png");
}
public void settings() {
size(800, 600);
}
public void keyPressed() {
if(key == 'w') {
shootUp = true;
}
if(key == 'a') {
shootLeft = true;
}
if(key == 's') {
shootDown = true;
}
if(key == 'd') {
shootRight = true;
}
}
public void draw() {
background(206);
imageMode(CENTER);
image(shooter, shooterX, shooterY);
if(shootUp == true) {
rect(shooterX, shooterY-u_bulletSpeed, 5, 5);
u_bulletSpeed += 2;
if(u_bulletSpeed > 300) {
u_bulletSpeed = 0;
shootUp = false;
}
}
if(shootLeft == true) {
rect(shooterX-l_bulletSpeed, shooterY, 5, 5);
l_bulletSpeed += 2;
if(l_bulletSpeed > 400) {
l_bulletSpeed = 0;
shootLeft = false;
}
}
if(shootDown == true) {
rect(shooterX, shooterY+d_bulletSpeed, 5, 5);
d_bulletSpeed += 2;
if(d_bulletSpeed > 300) {
d_bulletSpeed = 0;
shootDown = false;
}
}
if(shootRight == true) {
rect(shooterX+r_bulletSpeed, shooterY, 5, 5);
r_bulletSpeed += 2;
if(r_bulletSpeed > 400) {
r_bulletSpeed = 0;
shootRight = false;
}
}
}
}
The language is processing and I am using the eclipse IDE.
Thanks!
Here's what I would do if I were you. First I'd encapsulate your bullet data into a class, like this:
class Bullet{
float x;
float y;
float xSpeed;
float ySpeed;
// you probably want a constructor here
void drawBullet(){
// bullet drawing code
}
}
Then I'd create an ArrayList that holds Bullet instances:
ArrayList<Bullet> bullets = new ArrayList<Bullet>();
To add a bullet, I'd create a new instance and add it to the ArrayList like this:
bullets.add(new Bullet(bulletX, bulletY));
Then to draw the bullets, I'd iterate over the ArrayList and call the corresponding function:
for(Bullet b : bullets){
b.drawBullet();
}
Shameless self-promotion:
Here is a tutorial on creating classes.
Here is a tutorial on using ArrayLists.
I am working on a Processing project, but I donĀ“t know how to restart the project once it is over. I have searched and found that the setup() method will make it. But it's not working. Can anyone help me. I would like the sketch to restart by itself once it is finished.
/* OpenProcessing Tweak of *#*http://www.openprocessing.org/sketch/59807*#* */
/* !do not delete the line above, required for linking your tweak if you upload again */
//
// outline: takes an image (image.jpg) and creates a sketch version
//
// procsilas (procsilas#hotmail.com / http://procsilas.net)
//
String iName="image.jpeg";
void setup() {
llegeixImatge("./"+iName);
size(img.width, img.height);
}
// parameters
// NO real control, so be careful
int NP=6000; // 1000 for line art, 10000 for complex images, O(N^2) so be patient!!!
int B=1; // try 2 or 3
float THR=28; // range 5-50
float MD=6; // range 0-10
int NMP=6; // range 1-15
float[][] punts;
color[] cpunts;
int [] usat;
int [] NmP=new int[NMP];
float [] NdmP=new float[NMP];
int inici=0;
PImage img;
void llegeixImatge(String s) {
img = loadImage(s);
img.loadPixels();
}
float fVar(int x, int y) {
// neighborhood 2B+1x2B+1 pixels
float m=0;
for (int k1=-B; k1<=B; k1++) {
for (int k2=-B; k2<=B; k2++) {
color c=img.pixels[(y+k1)*img.width+(x+k2)];
m+=brightness(c);
}
}
m/=float((2*B+1)*(2*B+1));
float v=0;
for (int k1=-B; k1<B; k1++) {
for (int k2=-B; k2<B; k2++) {
color c=img.pixels[(y+k1)*img.width+(x+k2)];
v+=(brightness(c)-m)*(brightness(c)-m);
}
}
v=sqrt(v)/(float) (2*B+1);
return v;
}
void creaPunts() {
punts = new float[NP][2];
cpunts = new color[NP];
usat = new int[NP];
int nint1=0;
int nint2=0;
for (int i=0; i<NP;) {
int x=B+int(random(width-2*B));
int y=B+int(random(height-2*B));
//println(i+" = "+x+", "+y+": "+THR+", "+MD);
// points need to be at least MD far from each other
int flag=0;
if (MD>0.0) {
for (int j=0; flag==0 && j<i; j++) {
if (dist(x, y, punts[j][0], punts[j][1])<MD) {
flag=1;
}
}
}
if (flag==0) {
nint1=0;
float f=fVar(x, y);
// use only "valid" points
if (f>=THR) {
nint2=0;
punts[i][0]=x;
punts[i][1]=y;
cpunts[i]=img.pixels[y*img.width+x];
usat[i]=0;
i++;
}
else {
nint2++;
if (nint2>=10) {
THR/=(1+1.0/float(NP-i));
MD/=(1+1.0/float(NP-i));
nint2=0;
}
}
}
else {
nint1++;
if (nint1>=10) {
MD/=2.0;
THR*=1.618;
nint1=0;
}
}
}
}
int NessimMesProper(int i) {
if (NMP<=1) {
int mP=-1;
float dmP=dist(0, 0, width, height);
for (int j=0; j<NP; j++) {
if (usat[j]==0) {
float jmP=dist(punts[i][0], punts[i][1], punts[j][0], punts[j][1]);
if (jmP<dmP) {
dmP=jmP;
mP=j;
}
}
}
return mP;
}
else {
for (int j=0; j<NMP; j++) {
NmP[j]=-1;
NdmP[j]=dist(0, 0, width, height);
}
for (int j=0; j<NP; j++) {
if (usat[j]==0) {
float jmP=dist(punts[i][0], punts[i][1], punts[j][0], punts[j][1]);
int k=NMP;
while(k>0 && NdmP[k-1]>jmP) {
k--;
}
if (k<NMP) {
for (int l=0; l<(NMP-k)-1; l++) {
NmP[(NMP-1)-l]=NmP[(NMP-1)-(l+1)];
NdmP[(NMP-1)-l]=NdmP[(NMP-1)-(l+1)];
}
NmP[k]=j;
NdmP[k]=jmP;
}
}
}
return NmP[NMP-1];
}
}
int fase=0;
void draw() {
if (fase==0) {
creaPunts();
background(#FFFFFF);
fase=1;
}
else {
if (inici!=-1) {
stroke(#000000);
usat[inici]=1;
int seguent=NessimMesProper(inici);
if (seguent!=-1) {
line(punts[inici][0], punts[inici][1], punts[seguent][0], punts[seguent][1]);
}
inici=seguent;
}
else {
//save("outline_"+iName);
}
}
}
You should not call setup() yourself.
Step 1: Encapsulate the state of your program in a set of variables.
Step 2: Use those variables to draw your sketch.
Step 3: Modify those variables to change what's being drawn.
Step 4: Simply reset those variables to their initial values when you want to reset the sketch.
Here's an example program that stores its state (the positions the user has clicked) in an ArrayList. It uses that ArrayList to draw the sketch, and new points are added whenever the user clicks. When the user types a key, the sketch is reset by clearing out the ArrayList:
ArrayList<PVector> points = new ArrayList<PVector>();
void setup(){
size(500, 500);
}
void draw(){
background(0);
for(PVector p : points){
ellipse(p.x, p.y, 20, 20);
}
}
void mousePressed(){
points.add(new PVector(mouseX, mouseY));
}
void keyPressed(){
points.clear();
}
So I currently have a working 'Speed' power up that multiplies the speed of the player by 2. I'm trying to make a power up now that increases the score you get for picking up the GameObject 'Gem' by 2. it should increase to 20 points per gem from 10.
Currently, the power up is spawning randomly around the map within 10-20 seconds, so as intended, but the score you get for collecting the power up has not gone up to 20.
PlayerMovement Code:
public float speed = 10f;
private Rigidbody2D rb2d;
public GameObject Player;
public GameObject speedPowerUp;
public static int livess = 100;
public Vector2 movement;
public GameObject MultiPowerUp;
public static int addScore = 10;
void Start ()
{
rb2d = GetComponent<Rigidbody2D> ();
}
void FixedUpdate ()
{
float moveHorizontal = Input.GetAxis ("Horizontal"); //Gets keys that unity refers to being able to move horizontal (Set by default)
float moveVertical = Input.GetAxis ("Vertical"); //Gets keys that unity refers to being able to move vertical (Set by default) Use forces to act with RigidBody2D
Vector2 movement = new Vector2 (moveHorizontal, moveVertical);
rb2d.AddForce (movement * speed);
if(moveHorizontal < 0)
GetComponent<SpriteRenderer>().flipX = true;
else if(moveHorizontal > 0)
GetComponent<SpriteRenderer>().flipX = false;
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.CompareTag ("shuriken"))
{
if (livess <= 1)
{
Destroy (Player);
livess = livess - 1;
Debug.LogError (livess);
}
else
{
livess = livess - 1;
Debug.LogError (livess);
return;
}
}
if (other.gameObject.CompareTag ("speedPowerUp"))
{
StartCoroutine (WaitTimeSpeed ());
other.gameObject.SetActive (false);
}
if (other.gameObject.CompareTag ("MultiPowerUp"))
{
StartCoroutine (WaitTimeMulti ());
other.gameObject.SetActive (false);
}
}
IEnumerator WaitTimeSpeed ()
{
Debug.LogError (speed);
speed = speed * 2;
Debug.LogError (speed);
yield return new WaitForSeconds (5);
speed = speed / 2;
Debug.LogError (speed);
yield return new WaitForSeconds (Random.Range (10, 20));
SpawnSpeed ();
}
void SpawnSpeed()
{
Vector3 RandomSpawn = new Vector3 (Random.Range (-8.87F, 8.87F), Random.Range (-3.87F, 3.97F),1F);
Instantiate (speedPowerUp, RandomSpawn, Quaternion.identity);
}
IEnumerator WaitTimeMulti()
{
Debug.LogError (addScore);
addScore = 20;
Debug.LogError (addScore);
yield return new WaitForSeconds (5);
addScore = 10;
yield return new WaitForSeconds (Random.Range (10, 20));
SpawnMulti ();
}
void SpawnMulti ()
{
Vector3 RandomSpawn = new Vector3 (Random.Range (-8.87F, 8.87F), Random.Range (-3.87F, 3.97F),1F);
Instantiate (MultiPowerUp, RandomSpawn, Quaternion.identity);
}
}
Gem Code:
public GameObject Gem;
public static int count;
public Text countText;
public int addScores = PlayerMovement.addScore;
void Start()
{
SetCountText ();
}
void SpawnGem()
{
Vector3 RandomSpawn = new Vector3 (Random.Range (-8.87F, 8.87F), Random.Range (-3.87F, 3.97F),1F);
Instantiate (Gem, RandomSpawn, Quaternion.identity);
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.CompareTag ("Player"))
{
SpawnGem ();
count = count + addScores;
SetCountText ();
PlayerPrefs.SetInt("Player Score", count);
Destroy (Gem);
}
}
void SetCountText()
{
countText.text = "Count: " + count.ToString ();
}
}
I am making a 2d side scrolling game and I'm stuck. Im writing the class for the objects which will spawn increasingly and which the Player has to avoid. But sadly I am getting a Nullpointerexception and I cannot figure out why.Before I cleaned up the code in the main and transformed it to a class, the whole thing was working. I think I'm initializing the Array correctly and no variables are left undefined. I've only been using processing for the past months so I might have overseen something.
Thanks a lot for your help
public class Blockfield {
private int Blockcount;
private PImage Blockpic;
private Block block[];
//Constructor
public Blockfield (int Blockcount) {
this.Blockcount = Blockcount;
//new array
block = new Block [Blockcount];
for ( int i=0; i < Blockcount; i++) {
block[i] = new Block( width+Blockpic.width, random (height));
}
}
//Draw method for this class
public void draw () {
for (int i =frameCount/100; i >0; i--) {
image ( Blockpic, block[i].x, block[i].y);
//moves blocks right to left
block[i].x -=7 ;
//spawns block when they leave the screen
if (block[i].x < 0) {
block[i] = new Block( width+Blockpic.width, random (height));
}
}
}
}
class Block {
float x, y;
Block ( float x, float y) {
this.x= x;
this.y= y;
}
}
Main:
Blockfield blockfield;
PImage Blockpic;
void setup () {
size (1291, 900);
blockfield = new Blockfield(100);
Blockpic = loadImage("block2.png");
}
void draw () {
background ( 10);
}
The problem was that I was trying access Blockpic.width in your Blockfield constructor before Blockpic had been assigned. The solution was to load the Image within the constructor of the class.
Working code:
public class Blockfield {
private int Blockcount;
private PImage Blockpic;
private Block block[];
//Constructor
public Blockfield (int Blockcount) {
this.Blockcount = Blockcount;
Blockpic = loadImage("block2.png");
//new array
block = new Block [Blockcount];
for ( int i=0; i < Blockcount; i++) {
block[i] = new Block( width+Blockpic.width, random (height));
}
}
//Draw method for this class
public void draw () {
for (int i =frameCount/100; i >0; i--) {
image ( Blockpic, block[i].x, block[i].y);
//moves blocks right to left
block[i].x -=7 ;
//spawns block when they leave the screen
if (block[i].x < 0) {
block[i] = new Block( width+Blockpic.width, random (height));
}
}
}
}
class Block {
float x, y;
Block ( float x, float y) {
this.x= x;
this.y= y;
}
}
Thanks to everyone for the help!!!