We are about to switch to a new forum software. Until then we have removed the registration on this forum.
I want to make one of the games where your constantly falling, not necessarily in processing, I was just messing around with the basic mechanics, theres a coin class and a player class. How do I make it so when the player hits the coin something happens, like right now I just want the coin to be replaced by a different color with destroy(). thanks for any help! :)
Heres the code
Player player;
Coin coin;
void setup() {
size(500,500);
background(0);
player = new Player(width/2,0);
coin = new Coin();
}
void draw() {
background(0);
player.display();
player.update();
if (keyPressed) {
if (key == 'a' || key == 'A') {
player.location.x -= 1;
}
else if (key == 'd' || key == 'D') {
player.location.x += 1;
}
}
coin.update();
coin.display();
// coin.destroy(); //
}
class Player {
float gravity;
float speed;
PVector location;
Player(float x, float y) {
location = new PVector();
location.x = x;
location.y = y;
gravity = 0.28;
speed = 1;
}
void update() {
location.y = location.y + gravity;
if (location.y > height) {
location.y = 0;
}
}
void display(){
fill(#F02727);
rect(location.x, location.y, 15, 15);
}
}
class Coin {
float cx;
float cy;
boolean got;
Coin() {
got = false;
cx = 100;
cy = 200;
}
void update(){
if(player.location.x == cx && player.location.y == cy) {
got = true;
}
}
void display(){
fill(#F5E3E3);
ellipse(cx,cy,5,5);
}
void destroy() {
if(got = true){
fill(#F21111);
ellipse(cx,cy,5,5);
}
}
}
Answers
This should get you started
Here's my own take on it: ;))
Hey thanks guys! good tips
Hey gotoloop could you explain this to me :S
and thanks its better how you shortened it to player.script(); coin.script();
also the gravity as static float :)
Well, let's try. 1st off, I'm considering Coin as 1D shape and Player as 2D shape and p is player.loc.
cx > p.x
-> checking whether coin's x coordinate > player's left side location (comes after).cx < p.x + Player.DIM
-> whether coin's x coordinate < player's right side location (comes before).You see, for 2D shapes, we need to check their whole area. Just a merely coordinate pair won't cut it! [..]
cool thanks :) so I was wondering about using return, when you say return above it basically means return true? is it the same as saying
I was looking at the reference for return, don't get how to use it :-?
That whole expression evaluates as either true or false. Then its result is returned.
You can see for yourself hasHit() has been declared to return a
boolean
value anyways! <):)Keyword
return
forces a method to quit immediately. Either w/ some value or not.Here's
return
reference -> processing.org/reference/return.htmlP.S.: Since DIM is a static field, we can also access it using its own class name. Like ->
Player.DIM;
andCoin.DIM;
.DIM is after dimension word. But it's also the shape's diameter or both its width & height! ;)