ma903rh
Ex Member
small application to check object position
Apr 9th , 2010, 9:20am
Hi I am trying to do a simple sketch and having a samll problem. I have a car moved with mouseX and mouseY. I also have an array of object (small squares called MBox). I am comparing the position of the car with Mbox position, and I should increase car credit by 10 each time the car hit the box. I did that in a small funciton in MBox called: void checkCarPos() but it deosnot work well. sometimes ok and sometimes not Can any one help on this please? Thanks I dont know how to attach my code, but it is below: // main sketch int life = 100; Car myCar; MBox[] boxes = new MBox [1000]; int counter; PFont f; void setup (){ size (700, 500); f = loadFont ("ArialMT-48.vlw"); myCar = new Car(250,440); } void draw(){ background(100,163,46); write(); noCursor(); getBoxes(); generateBoxes(); myCar.display(); } void generateBoxes() { if (frameCount%160 == 0) { boxes[counter] = new MBox((int)random (width-200)); counter++; } } void getBoxes() { for (int i=0; i<counter;i++) { boxes[i].display(); boxes[i].move(); } } void write(){ fill (0); rect(625,250,150,500); textFont(f,12); // Specify font to be used fill(255); // Specify font color // Display Text text ( "Game Progress" ,555,260); text ( "Your Points: "+life ,555,280); } // Mbox class MBox{ int x; int y; int boxW; int boxH; boolean increment; MBox(int x){ this.x=x; this.y=0; this.boxW=20; this.boxH=15; increment=true; } void display (){ noStroke(); fill (255,0,0); rect(this.x-10,this.y-10,boxW,boxH); } void move(){ // while (this.live==true){ this.y+=2; checkCarPos(); // } }// end of move void checkCarPos() { /* if ((this.x-10 >= mouseX-15 && this.x+10 <= mouseX+15) || (this.x-10 >= mouseX-15 && this.x+10 <=mouseX+15 )&&(this.y-7 >mouseY-30 && this.y+7 <mouseY+30)) // if the box hit the care*/ println("------------ > -------------"); println("this.x"+ this.x); println("this.y"+this.y); println("mouseX"+mouseX); println("mouseY"+mouseY); if (this.x-10>mouseX-15 && this.x+10<mouseX+15 && this.y-7>mouseY-30 && this.y+7<mouseY+30 && this.increment) // if the box hit the care { life+=10; this.increment= false; } } } // Car public class Car{ //data color c; float x; float y; //conostructor Car(float xpos, float ypos) { this.x = xpos; this.y = ypos; } // function to move the car void display(){ rectMode (CENTER); // Car Body fill (100); if (mouseX > width - 165)// outside the border of the game { rect (530,mouseY,30,60); fill(0); rect (530-14, mouseY-20,6,8); rect (530+14, mouseY-20,6,8); // Lower wheels rect (530-14, mouseY+20,6,8); rect (530+14, mouseY+20,6,8); } else { rect (mouseX,mouseY,30,60); // Car upper Wheels fill(0); rect (mouseX-14, mouseY-20,6,8); rect (mouseX+14, mouseY-20,6,8); // Lower wheels rect (mouseX-14, mouseY+20,6,8); rect (mouseX+14, mouseY+20,6,8); } } }