Cant get collisions to work for Mario-like game - processing

so, I've spent a fair few hours on my Mario-like game but recently I've been stuck on the collisions after I changed to an object based collision system that seems like it should work but there is a bug somewhere that i cant find.
currently the box that represents the player just falls straight through the platform rather than sitting on the platform
You wont be able to run this snippet because I'm new to stack overflow and couldn't find anything closer to processing.
Here is the box class that has all my collision detection
//Box class -- THIS IS WHERE I NEED HELP -- everything else is just for context
//Box class
class Box {
private float xpos, ypos, sizeX, sizeY;
private float bottom = ypos + sizeY;
private float top = ypos;
private float left = xpos;
private float right = xpos + sizeX;
Box(float startX, float startY, float xSize, float ySize) {
boxes++;
xpos = startX;
ypos = startY;
sizeX = xSize;
sizeY = ySize;
}
void update() {
rect(xpos, ypos, sizeX, sizeY);
}
void collision() {
//If on box level
if (player.playerY + player.playerHeight >= top && player.playerY <= bottom) {
//Left Side
if ((player.playerX + player.playerWidth) <= left && (player.playerX + player.playerWidth) + speed >= left) {
player.playerX = left - player.playerWidth;
player.canMoveRight = false;
}
//Right Side
if (player.playerX >= right && player.playerX + speed <= right) {
player.playerX = right;
player.canMoveLeft = false;
}
}
//If in box Y coord
if (player.playerX + player.playerWidth >= left && player.playerX <= right) {
//top
if (player.playerY + player.playerHeight <= top && player.playerY + player.yVelocity + gravity >= top) {
player.Gravity = false;
player.playerY = top - player.playerHeight;
player.yVelocity = 0;
player.canMoveDown = false;
}
//bottom
if (player.playerY + player.yVelocity >= bottom && player.playerY + player.yVelocity + gravity <= bottom) {
player.canMoveUp = false;
player.yVelocity = 0;
player.playerY = bottom;
}
}
//onGround
if (player.playerY == ypos - player.playerHeight) {
player.onGround = true;
}
}
}
Control structure for multiple keypresses
//Control structure to enable multiple keypresses
//Control
float speed = 4;
float gravity = 1;
float jump = 10;
boolean isUp, isLeft, isDown, isRight;
void control() {
//Controls
if (isUp) {
if (player.canMoveUp) {
if (player.onGround) {
player.Gravity = true;
player.yVelocity = 0 + jump;
player.onGround = false;
}
}
}
if (isDown) {
if (player.canMoveDown) {
}
}
if (isRight) {
if (player.canMoveRight) {
player.playerX += speed;
}
}
if (isLeft) {
if (player.canMoveLeft) {
player.playerX -= speed;
}
}
if (player.onGround) {
player.Gravity = false;
player.yVelocity = 0;
}
}
void keyPressed() {
setMove(keyCode, true);
}
void keyReleased() {
setMove(keyCode, false);
}
boolean setMove(int k, boolean b) {
switch (k) {
case UP:
return isUp = b;
case DOWN:
return isDown = b;
case LEFT:
return isLeft = b;
case RIGHT:
return isRight = b;
default:
return b;
}
}
Main tab, box/entity updates and player class
//Main tab
float boxes = 0;
//Calls classes
Box b = new Box(0, 700, 800, 100);
Box b1 = new Box(300, 675, 25, 25);
Player player = new Player(50, 400, 20, 20);
void setup() {
size(800, 800);
frameRate(60);
}
void draw() {
background(255, 255, 255);
boxesUpdate();
boxesCollision();
entityUpdate();
control();
println(player.playerX + ", " + player.playerY);
println(player.yVelocity + ", " + player.Gravity + ", " + player.onGround + ", " + player.canMoveDown);
}
//Box collision update method for when i add more boxes
void boxesCollision() {
player.Gravity = true;
player.canMoveUp = true;
player.canMoveDown = true;
player.canMoveLeft = true;
player.canMoveRight = true;
player.onGround = false;
b.collision();
b1.collision();
if (player.Gravity) {
player.playerY += player.yVelocity;
player.yVelocity += gravity;
}
}
//Along with another update method for the other parts of the boxes
void boxesUpdate() {
b.update();
b1.update();
}
//Entity update method to update players and for when i add NPCs and enemies
void entityUpdate() {
player.update();
}
//Player class
class Player {
private float playerX, playerY, playerWidth, playerHeight;
private float yVelocity = 0;
private float xVelocity = 0;
private boolean canMoveRight, canMoveLeft, canMoveUp, canMoveDown;
private boolean onGround, Gravity;
Player(float X, float Y, float xSize, float ySize) {
playerWidth = xSize;
playerHeight = ySize;
playerX = X;
playerY = Y;
}
void update() {
rect(playerX, playerY, playerWidth, playerHeight);
}
}

Related

I'm trying to get pvectors used in the second frame, but nothing pops up anywhere for the pvector (Used circle too)

I can't see where the circle and not sure what's wrong with my code to make it so I can't see the circle with gravity that I coded. Wondering where I went wrong and what I could do to improve it. Can't seem to see what I've done wrong and I put the circle in gameState2 because I'm making the game in that gameState, gameState1 is for the introduction screen. I want to know why the circle won't appear when I use pvectors. If someone can please help me it would be greatly appreciated(this is an assignment for my class). I hope the comments help show the area in which I need help. (Also if someone could look over my code just for confirmation that I won't get bugs while trying to make the gravity.)
PImage background, backgroundGameState1, headbasketballbackground, player1, player2;
boolean moveRight, moveLeft, moveRight2, moveLeft2;
int canvasSizeX= 1000;
int canvasSizeY = 600;
int mainBackgroundX = 1000;
int mainBackgroundY = 600;
int gameState1 = 1;
int player1X = 100;
int player1Y = 200;
int player2X = 100;
int player2Y = 200;
int backgroundGameState1X= 1000;
int backgroundGameState1Y=600;
int time;
int player1MovmentX = 700;
int player2MovmentX = 100;
PVector Position = new PVector(250, 400);
PVector Velocity = new PVector(0, 0);
PVector Acceleration = new PVector(0, 5);
float elasticity = 0.8;
float airResistance = 0;
void setup() {
//size of canvas is 1000 on the X-axis by 600 on the y-axis
size(1000, 600);
//Loaded images and called them, also made sure to resize them in order to match the canvas size or to make program more asthetically pleasing
background = loadImage("headbasketballbackground.png");
background.resize(mainBackgroundX, mainBackgroundY);
backgroundGameState1 = loadImage("backgroundgamestate1.png");
backgroundGameState1.resize(backgroundGameState1X, backgroundGameState1Y);
player1 = loadImage("steph.png");
//resized image for the steph curry png
player1.resize(player1X, player1Y);
player2 = loadImage("kobe.png");
//resized the png
player2.resize(player2X, player2Y);
time=millis();
}
void draw() {
if (gameState1 == 1) {
background(backgroundGameState1);
if (millis() > time + 1000) {
text("Click On Space To Enter The Game!", 100, 100);
textSize(50);
// delay(3000); Used as a test to see how the delay would work and found it to be extremely slow so I increased it to 1000 milliseconds
}
drawGameState1();
}
if (gameState1 == 2) {
background(background);
image(player1, player1MovmentX, 300);
image(player2, player2MovmentX, 300);
}
if (player1MovmentX < 30) {
player1MovmentX = 40;
}
if (player1MovmentX > 930) {
player1MovmentX = 920;
}
if ( player2MovmentX < 30) {
player2MovmentX = 40;
}
if (player2MovmentX > 930) {
player2MovmentX = 920;
}
// if (gameState2 == 3) {
// text("Congrats you won!");
//}
}
void drawGameState1() {
}
void drawGameState2() {
drawBall();
checkIfBallHitEdge();
moveBall();
drawPlayer1Movment();
drawPlayer2Movment();
//drawBoundaries();
}
void drawGameState3() {
}
void drawPlayer1Movment() {
if (moveRight) {
player1MovmentX += 25;
}
if (moveLeft) {
player1MovmentX -= 25;
}
}
void drawPlayer2Movment() {
if (moveRight2) {
player2MovmentX += 25;
}
if (moveLeft) {
player2MovmentX -= 25;
}
}
//pvectors used here
void drawBall() {
ellipse(Position.x, Position.y, 30, 30);
}
void moveBall() {
Velocity = Velocity.add(Acceleration);
Velocity = Velocity.mult((1-airResistance)); // This slows the ball down a little bit each instant
Position = Position.add(Velocity);
}
//pvectors end here
void checkIfBallHitEdge() {
if (Position.x < 0 || Position.x > width) {
Velocity.x *= -1;
}
if (Position.y < 0) {
Velocity.y *= -1;
}
if (Position.y > height) { // Strikes the ground
Velocity.y *= -elasticity;
Position.y = height;
}
}
void keyPressed() {
if (gameState1 == 1) {
if (keyCode == 32) {
gameState1 = 2;
}
} else if (gameState1 == 2) {
if (keyCode == RIGHT) {
moveRight = true;
player1MovmentX += 25;
}
if (keyCode == LEFT) {
moveLeft = true;
player1MovmentX -= 25;
}
if (keyCode == 68) {
moveRight2 = true;
player2MovmentX += 25;
}
if (keyCode == 65) {
moveLeft2 = true;
player2MovmentX -= 25;
}
if (keyCode == UP) {
Velocity.y = -70;
}
}
}
void keyReleased() {
if (keyCode == RIGHT) {
moveRight = false;
}
if (keyCode == LEFT) {
moveLeft = false;
}
if (keyCode == 68) {
moveRight2 = false;
}
if (keyCode == 65) {
moveLeft2 = false;
}
}
I used the processing IDE for java.

My ball doesn't move smoothly but with stutters. How can I achieve smoother movement?

So this is processing project I have here https://www.openprocessing.org/sketch/672559 does work OK but the ball and the paddles don't really go very smooth when it goes faster. (you have to press the button to show the code on this page)
After a couple of bounces the ball becomes a bit jittery and I would like to know how to avoid that or make the whole movement smoother.
This is the code for the ball without the colors.
//ball variables
PVector ballVelocity = new PVector(0, 0); //velocity of ball
PVector ballPosition = new PVector(initial.x/2, initial.y/2); //position of ball
int maxPositions = 10; //the x positions
float radius = 10; //radius of ball
colour currentCol = new colour(255, 255, 255);
void placeBall() {
ballBeforePosition = new PVector(ballPosition.x, ballPosition.y);
ballPosition = new PVector(initial.x/2, initial.y/2);
ballPosition.x *= scalar.x;
ballPosition.y *= scalar.y;
ballVelocity.y = (float)(Math.random()*(10*scalar.y))-(4*scalar.y);
while (abs(ballVelocity.y)<1) ballVelocity.y = (float)(Math.random()*(10*scalar.y))-5;
if (!leftScored && rightScored) {
ballVelocity.x = 5 * scalar.x;
} else if (leftScored && !rightScored) {
ballVelocity.x = -5 * scalar.x;
} else {
if ((int)(Math.random()*2)==1) {
ballVelocity.x = 5 * scalar.x;
} else {
ballVelocity.x = -5 * scalar.x;
}
}
}
void accelerateBall(float acceleration) {
PVector newVelo = new PVector(ballVelocity.x * acceleration, ballVelocity.y * acceleration); //velocity of ball
ballVelocity = new PVector(newVelo.x, newVelo.y);
if (abs(ballVelocity.x)>(player1.dim().x+maxEndSpeed)) {
ballVelocity.x = sign(ballVelocity.x)*(player1.dim().x+maxEndSpeed);
return;
}
}
void decelerateBall(float deceleration){
PVector newVelo = new PVector(ballVelocity.x / deceleration, ballVelocity.y / deceleration); //velocity of ball
ballVelocity = new PVector(newVelo.x, newVelo.y);
if (abs(ballVelocity.x)< 5 * scalar.x) {
ballVelocity.x = sign(ballVelocity.x)*(5 * scalar.x);
return;
}
}
void runBallCollision(PVector pot, paddle p) {
if (collides(pot, p)) {
hitcount++;
firstcollision++;
if (firstcollision ==3) {
accelerateBall(1.5);
}
if ((p==player1&&pot.x > p.pos().x)||(p==player2&&pot.x < p.pos().x)) {
PVector tempVel = new PVector(ballPosition.x - p.pos().x, (ballPosition.y - p.pos().y)/5);
tempVel.normalize();
tempVel.mult(ballVelocity.mag());
ballVelocity = tempVel;
} else if (!sameSign(p.moveAmount(), ballVelocity.y)&&p.moveAmount()!=0) {
//p.speedBurst();
ballVelocity.x *= -1;
ballVelocity.y = abs(ballVelocity.y)*sign(p.moveAmount())+(p.moveAmount());
if (p==player1) {
ballPosition.x = p.pos().x + (p.dim().x) + radius;
}
if (p==player2) {
ballPosition.x = p.pos().x - (p.dim().x) - radius;
}
}
if (firstcollision<3 || firstcollision > 3 ) {
accelerateBall(1.05);
}
projected = false;
}
}
void moveBall() {
PVector potPos = PVector.add(ballPosition, ballVelocity);
runBallCollision(potPos, player1);
runBallCollision(potPos, player2);
if (potPos.y - radius <= 0+cornerwidth) {
ballVelocity.y *= -1;
} else if (potPos.y + radius >= height-cornerwidth) {
ballVelocity.y *= -1;
}
ballPosition.add(ballVelocity);
//GOAL
if (ballPosition.x<0+cornerwidth) {
rightScored = true;
leftScored = false;
reset(player2, true);
} else if (ballPosition.x>width-cornerwidth) {
rightScored = false;
leftScored = true;
reset(player1, true);
}
}
void displayBall() {
pushMatrix();
PVector newPosi = ballBeforePosition;
translate(ballPosition.x, ballPosition.y);
fill(currentCol.R(), currentCol.G(), currentCol.B());
noStroke();
rect(0, 0, radius*2, radius*2);
popMatrix();
}

Asteroids Game - Buggy Collision Detection

I am making an asteroid game using Processing 3.5.3. As you will see the collision detection is very buggy. When it detects collision between ship/asteroid sometimes it is greater than the asteroid size, sometimes it is smaller. Also, when the asteroids get smaller, the collision detect still seems to be calling the larger size asteroid. The collision between bullet and asteroid seems to only be a hit when the bullet is in the center of the asteroid.
Apologies for all the comments - they are required for my internal documentation.
Here is my code, it is broken up into classes.
Ship
class Ship {
PVector shipAcceleration;
PVector shipVelocity;
PVector shipPosition;
PShape shipShape;
float shipDirection;
int shipLastFire; //holds the time in millis that the last bullet was fired
int shipDelayTime;
Ship() {
shipAcceleration = new PVector();
shipVelocity = new PVector();
shipPosition = new PVector(width/2, height/2); // player starts in middle of screen
shipDirection = 0; // set to 0 to so "up" is a sense of direction
shipLastFire = 0;
shipDelayTime = 300;
keys = new boolean[5];
shipShape = createShape();
shipShape.beginShape();
shipShape.fill(255, 0, 0);
shipShape.vertex(0, -4);
shipShape.vertex(2, 0);
shipShape.vertex(2, 2);
shipShape.vertex(0, 1);
shipShape.vertex(-2, 2);
shipShape.vertex(-2, 0);
shipShape.vertex(0, -4);
shipShape.endShape();
}
void moveShip() {
shipShape.resetMatrix();
// reset.Matrix sourced from https://processing.org/reference/resetMatrix_.html
shipShape.rotate(radians(shipDirection)); // rotates ship
shape(shipShape, shipPosition.x, shipPosition.y, 10, 10);
}
void updateShip() {
// motion sourced from Chapter 22 of 'Processing: A programming handbook
// for visual designers and asrtists' by Casey Reas and Ben Fry
shipAcceleration.x = 0;
shipAcceleration.y = 0;
if (keys[0]) {
shipAcceleration.x = 0.5 * cos(radians(shipDirection) - PI/2);
shipAcceleration.y = 0.5 * sin(radians(shipDirection) - PI/2);
}
if (keys[1] && !keys[2])
{
shipDirection -= 5;
}
if (keys[2] && !keys[1])
{
shipDirection += 5;
}
shipVelocity.add(shipAcceleration);
// add sourced from https://processing.org/reference/PVector_add_.html
shipPosition.add(shipVelocity);
shipVelocity.mult(.95);
// mult sourced from https://processing.org/reference/PVector_mult_.html
shipPosition.x %= width;
if (shipPosition.x < -10)
{
shipPosition.x = width;
}
shipPosition.y %= height;
if (shipPosition.y < -10)
{
shipPosition.y = height;
}
if (keys[4]) {
if (millis() - shipLastFire > shipDelayTime) {
shipLastFire = millis();
fireBullet(shipPosition, shipVelocity, shipDirection);
}
}
}
}
Bullet
class Bullet {
PVector bulletPosition;
PVector bulletVelocity;
boolean bulletHidden; // used if lifespan is max and to help recycle
int bulletSize;
int bulletCreationTime;
int bulletLifespan; //the time in milli seconds that bullets last
int bulletSpeed;
Bullet() {
bulletHidden = true;
bulletSize = 5;
bulletPosition = new PVector();
bulletVelocity = new PVector();
bulletCreationTime = 0;
bulletLifespan = 3000;
bulletSpeed = 5;
}
void updateBullet() {
if (!bulletHidden) {
bulletPosition.add(bulletVelocity);
if (millis() - bulletCreationTime > bulletLifespan)
// millis sourced from https://processing.org/reference/millis_.html
{
bulletHidden = true;
}
bulletPosition.x %= width;
if (bulletPosition.x < -1)
{
bulletPosition.x = width;
}
bulletPosition.y %= height;
if (bulletPosition.y < -1)
{
bulletPosition.y = height;
}
}
}
void drawBullet() {
if (!bulletHidden) {
updateBullet();
ellipse(bulletPosition.x, bulletPosition.y, bulletSize, bulletSize);
}
}
void reset(PVector pos, PVector spe, float direct) {
bulletPosition = new PVector(pos.x + (20 * cos(radians(direct) - PI/2)), pos.y + (20 * sin(radians(direct) - PI/2)));
bulletVelocity.x = bulletSpeed * cos(radians(direct) - PI/2) + spe.x;
bulletVelocity.y = bulletSpeed * sin(radians(direct) - PI/2) + spe.y;
bulletCreationTime = millis();
bulletHidden = false;
}
}
Asteroid
class Asteroid {
float asteroidSize = (width/80*12);
float x;
float y;
float velocityX;
float velocityY;
PVector[] vertices = new PVector[8];
boolean active = true; //false after collision
int level = 1; // how many times has it been shot. Level 1 is not yet shot
Asteroid(float xPos, float yPos, int aLevel) {
if (xPos == 0 && yPos == 0) { //if begin level asteroids
x = random(width) ; // set random start positions
y = random (height);
} else { // if collision generating 2 smaller asteroids
x = xPos; // set from asteroid x, y
y = yPos;
}
velocityX = random(-2, 2);
velocityY = random(-2, 2);
level = aLevel; //sets asteroid level (how many times shot)
//create polygon. /aLevel generates smaller polygons with each collision.
vertices[0] = new PVector(random (width/80*3/aLevel), random(height/80*3/aLevel) );
vertices[1] = new PVector(random((width/80*4/aLevel), (width/80*8/aLevel)), random(height/80*3/aLevel) );
vertices[2] = new PVector(random((width/80*9/aLevel), (width/80*12/aLevel)), random(height/80*3/aLevel) );
vertices[3] = new PVector(random((width/80*9/aLevel), (width/80*12/aLevel)), random((height/80*4/aLevel), (height/80*8/aLevel)) );
vertices[4] = new PVector(random((width/80*9/aLevel), (width/80*12/aLevel)), random((height/80*9/aLevel), (height/80*12/aLevel)) );
vertices[5] = new PVector(random((width/80*4/aLevel), (width/80*8/aLevel)), random((height/80*9/aLevel), (height/80*12/aLevel)) );
vertices[6] = new PVector(random(width/80*3/aLevel), random((height/80*9/aLevel), (height/80*12/aLevel)) );
vertices[7] = new PVector(random(width/80*3/aLevel), random((height/80*4/aLevel), (height/80*8/aLevel)) );
}
void moveAsteroid() {
x = x + velocityX; //asteroids to move with a random velocity
y = y + velocityY;
if ( x < -1 * asteroidSize ) {
x = width + asteroidSize;
} //if off screen left, come back in right
if ( x > width + asteroidSize ) {
x = -1 * asteroidSize;
} // if off screen right, come back in left
if ( y < -1 * asteroidSize ) {
y = height + asteroidSize;
} //if off top of screen, come back in bottom
if ( y > height + asteroidSize ) {
y = -1 * asteroidSize ;
} //if off bottom of screen, come back in top
}
void asteroidDraw() {
if (active == false) { // If not active don't draw
return;
}
stroke(150);
fill(255);
// this was how I orginally coded. Have kept commented out for now, so I can see what I did, but will delete before submission.
/*beginShape();
vertex(vertices[0].x, vertices[0].y );
vertex(vertices[1].x, vertices[1].y );
vertex(vertices[2].x, vertices[2].y );
vertex(vertices[3].x, vertices[3].y );
vertex(vertices[4].x, vertices[4].y );
vertex(vertices[5].x, vertices[5].y );
vertex(vertices[6].x, vertices[6].y );
vertex(vertices[7].x, vertices[7].y );
endShape(CLOSE); */
beginShape();
for (PVector v : vertices) {
vertex(x+v.x, y+v.y);
}
endShape(CLOSE);
}
void manDown() {
active = false; //sets to in active so will stop drawing
// add 2 new asteroids to array
asteroids = (Asteroid[]) append( asteroids, new Asteroid( x+20, y+20, level + 1 ) ); // Appends asteroid to array. Changing level makes the asteroid smaller.
asteroids = (Asteroid[]) append( asteroids, new Asteroid( x-20, y-20, level + 1 ) ); // Appends two smaller asteroids to array.
}
}
Game Manager
class GameManager {
int scoreCount;
boolean gameState = true;
int lifeCount;
void newGame()
{
gameState = true; //sets game state to in play
scoreCount = 0; //set counter of flies killed to 0
lifeCount = 3;
}
void scoreUpdate()
{
textSize(width*3/100);
textAlign(LEFT);
fill(255);
text("Score " + scoreCount, (width*2/100), (height*4/100));
}
void lifeLost()
{
lifeCount = lifeCount - 1;
if (lifeCount <= 0) {
gameState = false;
gameOver();
}
}
void lifeUpdate()
{
textSize(height*3/100);
textAlign(LEFT);
fill(255);
text("Lives " + lifeCount, (width*2/100), ((height*4/100) + (height*3/100)) );
}
void gameOver()
{
background(0);
textSize(height*5/100);
textAlign(CENTER);
fill(255);
text("Game over", width/2, height/2.6);
//play again button
fill(255);
rect(((width/2)-(width/4)), (((height/2)- (height/12))), width/2, height/8);
fill(0);
text("Play Again", width/2, height/2);
//define area for play again button collision
if (mousePressed)
{
if (
(mouseX > width/4) &&
(mouseX < width/4 +width/2) &&
(mouseY > (height/2-height/10.5)) &&
(mouseY < ((height/2-height/10.5) + height/8))
)
{
setup(); //reset game
}
}
}
}
Main
Asteroid[] asteroids; //K Level 1 starts with 6, add 2 each level, 10 levels
Ship myShip;
GameManager gameManager;
ArrayList<Bullet> bullets;
// Array help sourced from chapter 28 of 'Processing: A programming handbook
// for visual designers and asrtists' by Casey Reas and Ben Fry
int bulletIndex; // used to recycle bullets
// index sourced from https://py.processing.org/reference/list_index.html
int startNum = 6; //K begin game with 6 asteroids in the level
boolean[] keys; // boolean for storing keypressed/released
void setup() {
size(800, 800);
gameManager = new GameManager();
gameManager.newGame();
bulletIndex = 0;
bullets = new ArrayList<Bullet>();
keys = new boolean[5];
myShip = new Ship();
asteroids = new Asteroid [startNum]; //K
for (int a = 0; a < startNum; a++) { //K create asteroids in array
asteroids[a] = new Asteroid(0, 0, 1); //K
}
for (int i = 0; i < 20; i++)
{
bullets.add(new Bullet()); // create bullets
}
}
void draw() {
background(0);
collisionDetect();
gameManager.gameState = true;
myShip.updateShip(); // E
myShip.moveShip(); // E
for (int a = 0; a < asteroids.length; a++) { //K for asteroids in array
asteroids[a].moveAsteroid(); //K
asteroids[a].asteroidDraw(); //K
}
gameManager.scoreUpdate();
gameManager.lifeUpdate();
for (int i = 0; i < bullets.size(); i++)
{
bullets.get(i).drawBullet(); // drawing bullets
}
}
void keyPressed() {
if (key == CODED) {
if (keyCode == UP)
keys[0] = true;
if (keyCode == LEFT)
keys[1] = true;
if (keyCode == RIGHT)
keys[2] = true;
if (keyCode == DOWN)
keys[3] = true;
} else {
if (key == 'w')
keys[0] = true;
if (key == 'a')
keys[1] = true;
if (key == 'd')
keys[2] = true;
if (key == 's')
keys[3] = true;
if (key == ' ')
keys[4] = true;
}
}
void keyReleased() {
if (key == CODED) {
if (keyCode == UP)
keys[0] = false;
if (keyCode == LEFT)
keys[1] = false;
if (keyCode == RIGHT)
keys[2] = false;
if (keyCode == DOWN)
keys[3] = false;
} else {
if (key == 'w')
keys[0] = false;
if (key == 'a')
keys[1] = false;
if (key == 'd')
keys[2] = false;
if (key == 's')
keys[3] = false;
if (key == ' ')
keys[4] = false;
}
}
void fireBullet(PVector pos, PVector spe, float dir) {
bullets.get(bulletIndex).reset(pos, spe, dir);
// set attributes of last used bullet
// get sourced from https://processing.org/reference/get_.html
bulletIndex++; //update index
bulletIndex %= bullets.size(); //keep index in range
}
void collisionDetect(){
Asteroid testHolder;
Bullet bulletHolder;
// asteroid and bullet objects to minimize creating new objects
for(int i = 0; i < asteroids.length; i++){
testHolder = asteroids[i];
if(dist(testHolder.x, testHolder.y, myShip.shipPosition.x,
myShip.shipPosition.y) < testHolder.asteroidSize)
// collision of player and the asteroid
{gameManager.gameOver();}
for(int j = 0; j < bullets.size(); j++){
bulletHolder = bullets.get(j);
// pull and store each bullet from the list
if(bulletHolder.bulletHidden){continue;}
// don't calculate anything if it is hidden
if(dist(testHolder.x, testHolder.y, bulletHolder.bulletPosition.x,
bulletHolder.bulletPosition.y) < testHolder.asteroidSize){
testHolder.manDown();
// used to detect collision and split if collided
bulletHolder.bulletHidden = true;
// hide the bullet so it won't go 'through' the asteroids
j++;
}
}
}
}
For the problem with the smaller asteroids, you need to make the asteroidSize dependent on the level. Currently they are all the same: float asteroidSize = (width/80*12);
As the to collision issue, the first thing is that you also have to take the size to the ship/bullet hitting the asteroid into account:
if(dist(testHolder.x, testHolder.y, myShip.shipPosition.x, myShip.shipPosition.y) < (testHolder.asteroidSize + myShip.size))
For clarity: size is in both cases the radius.
Second, there will always be some area's where this basic type of collision detection does not follow the visual, because your shapes are not circles. The randomness that you use for the asteroids does not help in that respect. A way to get more control over this is to define a couple of shapes per level, and pick one of those at random when creating an asteroid. This way you can tweak the shape/radius to make a good trade off between looks and function so it looks 'believable enough'.

Unable to run the program

I am making a game in Eclipse Mars using the Processing library. I had made the game elsewhere and it ran fine. There were no errors after I copied and pasted the files from my flash drive to the folder in Eclipse. When I tried to run it, it said "The selection cannot be launched, and there are no recent launches." There were no recent launches because I had just gotten Eclipse. My code is as follows:
Main Class:
//package dogeball;
import processing.core.PApplet;
import processing.core.PImage;
import java.awt.Color;
import processing.core.PFont;
public class Dogeball extends PApplet {
Ball ball;
Furniture butterChair;
Furniture[] bricks;
PFont dogefont;
float py;
float score;
boolean game;
int checker;
boolean mode;
PImage img = loadImage("doge.jpg");
PImage img2 = loadImage("doge2.png");
public void setup() {
checker = 0;
size(300,250);
game = false;
mode = true;
ball = new Ball(this, 100, 225, 0, 0, 10, Color.DARK_GRAY );
butterChair = new Furniture(this, 130, 238, 40, 10, Color.YELLOW);
py = butterChair.w /2;
bricks = new Furniture[56];
dogefont = loadFont("ComicSansMS-48.vlw");
for(int rowNum = 0; rowNum<8; rowNum+= 1) {
for(int colNum = 0; colNum<7; colNum += 1){
bricks[7*rowNum + colNum] = new Furniture(this, 10+40*colNum, 10+15*rowNum, 40, 15, Color.red);
score = 0;
}
}
}
public void draw() {
if(game == false) {
background(img);
fill(0,255,255);
textSize(30);
textFont(dogefont);
text("DogeBall",33, 170);
fill(255,255,0);
textSize(20);
text("Press Space", 120,190);
fill(255,0,0);
text("Such BrickBreaker", 20, 20);
fill(0,0,255);
text("Much Atari", 190, 80);
fill(0,255,0);
text("How Breakout", 150, 230);
}
if(keyPressed == true) {
if (key == ' ') {
game = true;
}
}
if(game == true) {
if(keyPressed == true) {
if (key == 'm') {
mode = !mode;
}
}
//checker = 0;
background(img);
ball.appear();
ball.hover();
butterChair.appear();
if(mode == true) {
butterChair.x = mouseX-butterChair.w/2;
}
if(mode == false) {
if(keyPressed == true) {
if (key == CODED) {
if (keyCode == LEFT){
butterChair.x -= 3;
}
}
}
if(keyPressed == true) {
if (key == CODED) {
if (keyCode == RIGHT){
butterChair.x += 3;
}
}
}
}
if(butterChair.x <= 0) {
butterChair.x = 0;
}
if(butterChair.x >= width - butterChair.w) {
butterChair.x = width - butterChair.w;
}
textFont(dogefont);
fill(255,0,255);
text("Much Doge", 12, 160);
fill(255,0,0);
textSize(20);
text("M to toggle mouse mode.", 20,200);
fill(0);
textSize(10);
text("You might have to press twice", 10,220);
fill(0,0,255);
textSize(20);
text("Press S to Start", 150, 230);
if (keyPressed == true) {
if (key == 's' || key == 'S'){
ball.vy = 2;
ball.vx = 1;
}
}
/*if(mousePressed == true) {
ball.vx = 0;
ball.vy = 0;
}*/
for(int i = 0; i<56; i+= 1) {
bricks[i].appear();
}
}
detectCollision();
if(ball.y >= height) {
checker = 0;
if(checker ==0){
background(img);
ball.vx = 0;
ball.vy = 0;
textSize(30);
fill(255,0,0);
game = false;
text("Such Sorry", 130, 160);
fill(0,255,255);
text("Much Game Over", 20, 215);
fill(255,255,0);
text("So Losing", 10, 30);
textSize(20);
text("Press P to Play Again", 20, 245);
}
if(keyPressed == true) {
if(key == 'p') {
game = true;
ball.x = 100;
ball.y = 225;
checker = 1;
for(int rowNum = 0; rowNum<8; rowNum+= 1) {
for(int colNum = 0; colNum<7; colNum += 1){
bricks[7*rowNum + colNum] = new Furniture(this, 10+40*colNum, 10+15*rowNum, 40, 15, Color.red);
score = 0;
}
}
}
}
}
}
void detectCollision() {
if(keyPressed == true) {
if(key == '-')
{
for(int cCode = 0; cCode < 56; cCode += 1) {
Furniture b = bricks[cCode];
b.x = width * 2;
b.y = height * 2;
score = 56;
}
}}
if(ball.x >= butterChair.x &&
ball.x <= butterChair.x + butterChair.w &&
ball.y + ball.s /2 > butterChair.y) {
ball.vy *= -1;
}
for(int i = 0; i<bricks.length; i+= 1) {
Furniture b = bricks[i];
if(ball.x >= b.x && ball.x <= b.x+b.w && ball.y-ball.s/2 <= b.y) {
b.y = height * 2;
b.x = width * 2;
ball.vy *= -1;
score += 1;
}
if(score == 56){
background(img);
ball.vx = 0;
ball.vy = 0;
fill(255,0,0);
textSize(20);
text("Such Winning!", 20, 20);
textSize(40);
fill(0,255,0);
text("Much Congrats!",12 ,160);
textSize(20);
fill(255,0,255);
text("Press P to Play Again", 20, 245);
if(keyPressed == true) {
if(key == 'p') {
game = true;
ball.x = 100;
ball.y = 225;
checker = 1;
for(int rowNum = 0; rowNum<8; rowNum+= 1) {
for(int colNum = 0; colNum<7; colNum += 1){
bricks[7*rowNum + colNum] = new Furniture(this, 10+40*colNum, 10+15*rowNum, 40, 15, Color.red);
score = 0;
}
}
}
}
}
}
}
static public void main(String args[]) {
PApplet.main("Dogeball");
}
}
Ball Class:
//package dogeball;
import java.awt.Color;
import processing.core.PApplet;
public class Ball extends PApplet {
float x;
float y;
float vx;
float vy;
float s;
Color c;
PApplet p;
Ball(PApplet pApp, float xLocation, float yLocation, float xSpeed, float ySpeed, float size, Color shade){
x = xLocation;
y = yLocation;
vx = xSpeed;
vy = ySpeed;
s = size;
c = shade;
p = pApp;
}
void hover() {
x += vx;
y += vy;
if(x< 0 || x> p.width) {
vx *= -1;
}
if(y< 0) {
vy *= -1;
}
}
void appear() {
p.fill(c.getRGB() );
p.ellipse(x,y,s,s);
}
}
Paddle Class:
//package dogeball;
import java.awt.Color;
import processing.core.PApplet;
public class Furniture extends PApplet {
float x;
float y;
float w;
float h;
Color c;
PApplet p;
Furniture(PApplet PApp, float locationX, float locationY, float fWidth, float fHeight, Color shade) {
x = locationX;
y = locationY;
w = fWidth;
h = fHeight;
c = shade;
p = PApp;
}
void appear() {
p.fill(c.getRGB());
p.rect(x,y,w,h);
}
}
You have probably the wrong project selected on the projects tree or the run configurations are set to another project, since you haven't run it yet.
Either way, you have to right click your projects folder on the projects tree, then find Run As > Java Applet.
Another way to do it would be adding a main function, as you already did, and run is as a Java Application. Instead of using the current main function, you can try to use the code below to see it in present mode and see if it works:
public static void main(String args[]) {
PApplet.main(new String[] { "--present", "Dogeball" });
}

XNA SpriteSheet not working

I have added logic to show the Sprite animating but it's simply not showing on the screen. What am I doing wrong?
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input.Touch;
namespace MyXNAGame.Game_Classes
{
public class Player : Sprite
{
private int _frameCount = 6;
private int _frameIndex;
private Rectangle[] _frames;
public float _jumpVelocity = 12f;
public PlayerState _playerState;
public Rectangle BoundingBox
{
get { return new Rectangle {X = (int) Position.X, Y = (int) Position.Y, Height = Texture.Height, Width = Texture.Width}; }
}
public void Initialize()
{
_frames = new Rectangle[_frameCount];
int width = Texture.Width / _frameCount;
for (int i = 0; i < _frameCount; i++)
{
_frames[i] = new Rectangle(i*width, 0, width, Texture.Height);
}
}
public void Load(ContentManager contentManager, string assetName)
{
Texture = contentManager.Load<Texture2D>(assetName);
}
public void Update(GameTime gameTime)
{
while (TouchPanel.IsGestureAvailable)
{
GestureSample gestureSample = TouchPanel.ReadGesture();
if (gestureSample.GestureType == GestureType.Tap)
{
if (_playerState == PlayerState.Running)
{
_playerState = PlayerState.NormalJump;
}
}
if (gestureSample.GestureType == GestureType.Hold)
{
if (_playerState == PlayerState.Running)
{
_playerState = PlayerState.LongJump;
}
}
}
// NormalJump Logic
switch (_playerState)
{
case PlayerState.NormalJump:
Position.Y -= _jumpVelocity;
_jumpVelocity -= 0.5f;
if (_jumpVelocity == 0)
{
_playerState = PlayerState.Falling;
}
break;
case PlayerState.LongJump:
Position.Y -= _jumpVelocity;
_jumpVelocity -= 0.5f;
if (_jumpVelocity == 0)
{
_playerState = PlayerState.Falling;
}
break;
case PlayerState.Falling:
Position.Y += _jumpVelocity;
_jumpVelocity += 0.5f;
break;
case PlayerState.Running:
_frameIndex++;
if (_frameIndex > 5)
{
_frameIndex = 0;
}
break;
}
}
public void Draw(SpriteBatch spriteBatch)
{
spriteBatch.Draw(Texture, Position, _frames[_frameIndex], Color.White, 0, new Vector2(0, 0), new Vector2(0, 0), SpriteEffects.None, 0);
}
}
}`
Can anyone see the obvious mistake? I am using WP7
I changed the 'Scale' parameter in the Draw() method from new Vector(0,0) to new Vector(1,1) as obviously, having a Scale of 0 will not show anything at all.

Resources