Hi so i have here a 'falling' style game where i have homer simpsons head falling through the sky avoiding the salads and collecting burgers to increase score. I have implemented collision detection so when homer hits a salad he should re-spawn and have a life deducted which works fine. However if homers head hits the side of the salad and not directly in the centre of it the game will freeze for a moment and then carry on like nothing happened. I am not sure why this happens and wondering if there is a problem with how i am doing this. Here is my code below:
Are the collision detection not accurate enough or is there another issue that i am missing?
PImage background;
PImage MenuBackground;
int y=0;//global variable background location
final int End = 0;
final int Active = 1;
final int Menu = 2;
int gameMode = Menu;
int score = 0;
int lives = 3;
Boolean BurgerCollisionInProgress = false;
Boolean BurgerCollisionInProgress2 = false;
Salad salad1;
Salad salad2;
Salad salad3;
Homer user1;
Burger Burger;
public void settings()
{
size(500,1000); //setup size of canvas
}
void menu()
{
background = loadImage("spaceBackground.jpg"); //image used for background
background.resize(500,1000); //resizes the background
gameMode = Active;
float rand = random(25,475);
int intRand = int(rand);
float rand2 = random(25,475);
int intRand2 = int(rand2);
float rand3 = random(25,475);
int intRand3 = int(rand3);
float rand4 = random(25,475);
int intRand4 = int(rand4);
user1 = new Homer(250,100); //declares new defender as user1
Burger = new Burger(intRand,900,2);
salad1 = new Salad(intRand2,900,3);
salad2 = new Salad(intRand3,900,3);
salad3 = new Salad(intRand4,900,3); //3 aliens declared with their x and y position and their speed they move at
draw();
}
void setup()
{
if(gameMode == 2)
{
MenuBackground = loadImage("simpMenu.png");
MenuBackground.resize(540,1000);
image(MenuBackground, 0, y);
textAlign(CENTER);
textSize(40);
fill(252, 3, 3);
text("Press 'p' to play", 250,500);
}
}
void draw ()
{
if (gameMode == Active)
{
if(crash() == false)
{
drawBackground();//calls the drawBackground method
textSize(32);
fill(22,100,8);
text("Score: " + score,75,40);
text("Lives: " + lives,75,80);
salad1.update();//calls the update method which holds the move and render methods for alien
salad2.update();
salad3.update();
user1.render();//calls the update method which holds the move and render methods for user
Burger.update();//calls the update method which holds the move and render methods for burger
if(Bcrash() == true && BurgerCollisionInProgress == false)
{
score = score+1;
BurgerCollisionInProgress = true;
Burger.y = 900;
float rand = random(25,475);
int intRand = int(rand);
Burger.x = intRand;
}
if(Bcrash() == false)
{
BurgerCollisionInProgress = false;
}
if(crash() == true && BurgerCollisionInProgress2 == false)
{
if (lives < 1)
{ gameMode = End;
textSize(28);
fill(22,100,8);
text("Game Over, press 'r' to restart",200,200);
}
else
{
lives = lives - 1;
BurgerCollisionInProgress2 = true;
menu();
}
if(crash() == false)
{
BurgerCollisionInProgress2 = false;
}
}
}
}
}
void drawBackground()
{
image(background, 0, y); //draw background twice adjacent
image(background, 0, y-background.width);
y -=2;
if(y == -background.width)
y=0; //wrap background
}
boolean crash()
{
if(user1.crash(salad1))
{
return true;
}
if(user1.crash(salad2))
{
return true;
}
if(user1.crash(salad3))
{
return true;
}
return false;
}
boolean Bcrash()
{
if(user1.crash(Burger))
{
return true;
}
return false;
}
Homer class:
class Homer
{
PImage UserImage;
int x,y; //declaring variables
Homer(int x, int y)
{
this.x = x;
this.y = y;
UserImage = loadImage("homer.png");
UserImage.resize (60, 52);
} // end of Homer
void render()
{
//draw a Homer
image(UserImage,x,y);
} //end of void render
boolean crash(Salad A)
{
if((abs(x-A.x)<=30) && abs(y-A.y)<=30)
{
return true;
}
return false;
}// end of crash
boolean crash(Burger A)
{
if((abs(x-A.x)<=30) && abs(y-A.y)<=30)
{
return true;
}
return false;
}
} // end of class
Burger Class:
class Burger
{
PImage burgerImage;
int x,y, speedX;
int speedY = 0;
Burger(int x, int y, int speedY)
{
this.x = x;
this.y = y;
this.speedY= speedY;
burgerImage = loadImage("food.png");
burgerImage.resize (60, 52);
}
void render()
{
image(burgerImage,x,y);
}
void move()
{
y = y - speedY;
float rand = random(25,475);
int intRand = int(rand);
if(this.y < 0)
{
this.y = 900;
this.x = intRand;
}
}
void update()
{
move();
render();
}
}
Salad Class:
class Salad
{
float x,y;
float speedX, speedY; //declaring variables
PImage saladImage;
Salad(int x, int y, int speedY)
{
this.x = x;
this.y = y;
this.speedY = speedY;
saladImage = loadImage("salad.png");
saladImage.resize (60, 52);
} //end of salad
void move()
{
y=y-speedY;
float stepY = random(-5,5);
y = y + (int)stepY;
float rand = random(25,475);
int intRand = int(rand);
if(this.y < 0)
{
this.y = 900; // once the salads y is less than 0 they restart at 900
this.x = intRand;
speedY = speedY + 0.5;
}
} //end of void move
//draw a salad
void render()
{
image(saladImage,x,y);
} //end of void render
void update()
{
move();
render();
}
}// end of alien class
There are several little things which makes this harder than it could be. First, your intersect method isn't quite right. Then, the way you handle coordinates could be improved upon.
What I'm going to do first is to show you how to intersect rectangles. After that, I'll show you how I would deal with the drawable objets so they stay easy to manipulate. Then I'll show you some skeleton code for a short, easy game with stuff falling and colliding, and just for you I'll add some help so you can implement these suggestions into the context of your game.
1. Collisions
There are many ways to handle collisions. Most of them are applied mathematics, some of them are clever algorithms making use of colors or invisible sprites. There are probably methods I'm forgetting, too.
We'll only do collisions between rectangles, as your program seems quite rectangle-friendly and it's the easier method. So we'll write a intersection detection algorithm.
First thing to do when writing an algorithm is the pseudocode. I'm not joking. It's easy to go all clakety-clak with your keyboard and hit compile. It works most of the time... but it's more intuitive logic than applying your brain to the problem.
Being able to pseudocode is like a superpower for programmers. Never underestimate it.
Now, how do you know if two rectangles are intersecting? The answer is:
There are 4 ways that two rectangles can intersect, whether horizontally or vertically.
They must intersect both horizontally and vertically to overlap for real.
These are the possibilities you have to look for:
Red rectangle is bigger than black rectangle and black rectangle is completely inside it.
Both rectangles overlap on the left side (horizontally) or on the top side (vertically).
Red rectangle small enough to be inside black rectangle.
Both rectangles overlap on the right side (horizontally) or on the bottom side (vertically).
Because this code can be used in many places, I took it out of context and put it inside a fonction which takes coordinates and returns a boolean (true if there indeed is a collision):
// INTERSECT RECTs
boolean intersect(float x1, float y1, float w1, float h1, float x2, float y2, float w2, float h2)
{
boolean checkX = x1 < x2 && x1+w1 > x2 || x1 < x2+w2 && x1+w1 > x2+w2 || x1 > x2 && x1+w1 < x2+w2 || x1 < x2 && x1+w1 > x2+w2;
boolean checkY = y1 < y2 && y1+h1 > y2 || y1 < y2+h2 && y1+h1 > y2+h2 || y1 > y2 && y1+h1 < y2+h2 || y1 < y2 && y1+h1 > y2+h2;
return checkX && checkY;
}
This is one way of handling collisions between rectangles. You could take this information and apply it to your game, and it would rock.
This said, you could also improve on your code with Inheritance...
2. Inheritance (in this case: for graphical objects)
Inheritance in computer science is a way to make a class obtain the properties of another one. Most people explains it in term of family: there is a parent class and there are children class which inherits the parent class' properties.
Inheritance is especially useful when several of your class share the same properties or methods. Drawable objects are a great example, because they all need coordinates. They all need a method to be drawn.
As you'll see with the example game later, I noticed that all my rectangles needed these modal variables:
protected float x, y, w, h; // x and y coordinate, width and height of the square
protected color fill, stroke;
protected float strokeWeight = 1;
So I created a base class named 'Drawable'. In a bigger project, it could be the base class of a whole tree of classes, like this:
So in this example, Rat would be the child of Walker, which is the child of Enemy, which is the child of Actor, which is the child of Drawable.
The advantage is that every child inherits everything from it's parent. It both makes you write less code and let you fix your mistakes in only one place instead of everywhere. For an example, if there's a mistake in how you use the coordinates of your objects, you want to fix it in the class where this logic is written, not in every class.
There are many other advantages to Inheritance, but for now let's keep it simple, all right?
3. Example program
This one is very straightforward: this is an example which use both inheritance and collisions. You can copy and paste it into a Processing IDE and it'll run. Take some time to see how the 3 classes relate to one another, and how every child class has the modal variables and functions of it's parent.
Hero hero;
ArrayList<Bomb> bombs = new ArrayList<Bomb>();
int numberOfBombs = 20; // if you change this number the number of bombs will change too. Try it!
int hitCount = 0;
public void settings()
{
size(800, 600); //setup size of canvas
}
public void setup() {
hero = new Hero();
for (int i = 0; i < numberOfBombs; i++) {
bombs.add(new Bomb(random(20, width-20), random(1, 10)));
}
// This part serves no purpose but to demonstrate that you can gather objets which share a parent class together
ArrayList<Drawable> myDrawables = new ArrayList<Drawable>();
for (Bomb b : bombs) {
myDrawables.add(b);
}
myDrawables.add(hero);
for (Drawable d : myDrawables) {
d.Render();
// Even though hero and the bombs are different classes, they are in the same ArrayList because they share the Drawable parent class.
// Drawable has the Render() function, which may be called, but the child class will overshadow the Drawable's method.
// Proof is that the error message "Drawable child: Render() was not overshadowed." will not appear in the console.
}
}
public void draw() {
DrawBackground();
hero.Update();
hero.Render();
for (Bomb b : bombs) {
b.Update();
b.Render();
}
ShowHitCount();
}
public void DrawBackground() {
fill(0);
stroke(0);
rect(0, 0, width, height, 0); // dark background
}
public void ShowHitCount() {
textAlign (RIGHT);
textSize(height/20);
fill(color(200, 200, 0));
text(hitCount, width-20, height/20 + 20);
}
class Drawable {
protected float x, y, w, h; // 'protected' is like 'private', but child class retain access
protected color fill, stroke;
protected float strokeWeight = 1;
Drawable() {
this(0, 0, 0, 0);
}
Drawable(float x, float y, float w, float h) {
this.x = x;
this.y = y;
this.w = w;
this.h = h;
}
public void Render() { print("Drawable child: Render() was not overshadowed."); } // nothing to see here: this exists so we can overshadow it in the childs
public void Update() { print("Drawable child: Update() was not overshadowed."); } // same thing
}
class Hero extends Drawable { // 'extends' is keyword for 'will inherit from'
Hero() {
// 'super()' calls the parent's constructor
// in this example, I decided that the hero would be a red 40x60 rectangle that follows the mouse X position
super(mouseX - 20, height - 80, 40, 60);
fill = color(200, 0, 0);
stroke = color(250);
}
public void Update() { // when both parents and child have the same function (type and signature), the child's one prevail. That's overshadowing.
x = mouseX - w/2;
}
public void Render() {
fill(fill);
stroke(stroke);
strokeWeight(strokeWeight);
rect(x, y, w, h);
}
}
class Bomb extends Drawable {
protected float fallSpeed;
Bomb(float xPosition, float fallSpeed) {
// Bombs will be small blue squares falling from the sky
super(xPosition, -20, 20, 20);
this.fallSpeed = fallSpeed;
fill = color(0, 0, 200);
stroke = fill;
}
private void FallAgain() {
x = random(20, width-20);
fallSpeed = random(1, 10);
y = 0 - random(20, 100);
}
public void Update() {
y += fallSpeed;
// check for collision with the Hero
if (intersect(x, y, w, h, hero.x, hero.y, hero.w, hero.h)) {
hitCount++;
FallAgain();
}
// check if it fell lower than the screen
if (y > height) {
FallAgain();
}
}
public void Render() {
fill(fill);
stroke(stroke);
strokeWeight(strokeWeight);
rect(x, y, w, h);
}
}
// INTERSECT RECTs
boolean intersect(float x1, float y1, float w1, float h1, float x2, float y2, float w2, float h2)
{
boolean checkX = x1 < x2 && x1+w1 > x2 || x1 < x2+w2 && x1+w1 > x2+w2 || x1 > x2 && x1+w1 < x2+w2 || x1 < x2 && x1+w1 > x2+w2;
boolean checkY = y1 < y2 && y1+h1 > y2 || y1 < y2+h2 && y1+h1 > y2+h2 || y1 > y2 && y1+h1 < y2+h2 || x1 < y2 && y1+h1 > y2+h2;
return checkX && checkY;
}
4. Bonus: help with implementation
So... you're seeing this and it makes you want to improve on your program. That's good. Maybe you want to implement some inheritance, maybe just the collisions. Both can be tricky, and neither is supposed to impact the user.
This is what is called 'refactoring'.
Let's implement a Drawable class first. The rest will be easier then.
First step: find what's the common ground with Burger, Homer and Salad. From the code you posted, I can see that they need these things:
int x, y;
int speedX, speedY;
PImage img;
// To which I would add:
int w, h;
boolean isVisible;
I notice that you're using integers. That's fine, but I strongly suggest using float for coordinates. I did the same thing when I was learning to code and I ended up regretting not using float earlier. Both integer and float will probably do the trick for this project (with some cast when needed).
Also, here are a couple functions that they share:
void Render()
void Update()
void Move()
// To which I would add:
void SetPosition()
void SetIsVisible()
boolean Crash() // so we can check if it intersect with given coordinates
So far, your Drawable class could look like this:
class Drawable {
public float x, y, w, h; // Making variables public while you could avoid it is bad practice, I'm doing it to avoid writing Get functions. Avoid doing this as much as possible, but bear with me for now.
protected float speedX, speedY;
protected PImage img;
protected boolean isVisible = true;
Drawable(float x, float y, float w, float h, String imagePath) {
this.x = x; // starting x position
this.y = y; // starting y position
this.w = w; // width if the object (your image in this case)
this.h = h; // height of the object (height of your image)
if (imagePath.length() > 0) { // if there is nothing in the string it won't try to load an image
img = loadImage(imagePath);
}
}
public void Render() {
if (isVisible && img != null) {
image(img, x, y);
}
}
public void Update() {
Move(); // I kept Move() out of Update() so you can overshadow Update() without having to re-code Move() later
}
protected void Move() {
// The 'normal' behavior of a Drawable would then to move according to it's speed.
// You can then change how they move by changing their speed values.
// Or... you can overshadow this function in a child class and write your own!
x += speedX;
y += speedY;
}
public void SetPosition(float x, float y) {
this.x = x;
this.y = y;
}
public void SetIsVisible(boolean isVisible) {
this.isVisible = isVisible;
}
public boolean Crash(float x, float y, float w, float h) {
// this function uses the 'intersect' function I wrote earlier, so it would have to be included in the project
return intersect(this.x, this.y, this.w, this.h, x, y, w, h);
}
}
Not so bad so far, isn't it? This will make a strong base for all your objects. Now, let's see how to implement this into your existing class:
Homer:
class Homer extends Drawable // give Homer the power of the Drawable class!
{
Homer(float x, float y)
{
// I can read in the code that your image will be (60, 52), but you have to write the manipulation here
super(x, y, 60, 52, "homer.png");
img.resize (60, 52);
}
public void Update() {
// do Update stuff so Homer can move around
}
}
Notice how smaller this class is now that all the Drawable stuff is dealt elsewhere.
Now, here's for the Salad class:
First, you can drop the salad1, salad2, salad3 global variables. We'll put them in a list, and you'll be able to have more or less of them if you want (you can think of this as being able to change the difficulty setting):
int numberOfSalads = 3;
ArrayList<Salad> salads = new ArrayList<Salad>();
In the place where you innitialize the salads, you can initialize them in a loop:
for (int i=0; i<numberOfSalads; i++) {
salads.add(new Salad(random(25,475), 900, 3);
}
Sure, there will be some modifications to make to the Salad class, too:
class Salad extends Drawable {
Salad(float x, float y, float speedY)
{
super(x, y, 60, 52, "salad.png");
this.speedY = speedY; // Drawable will take it from here
img.resize (60, 52);
}
protected void Move() // I knew this would come in handy!
{
// I have no idea what's going on, just re-writing your stuff
y = y - speedY;
y = y + random(-5, 5);
if (this.y < 0)
{
this.y = 900; // once the salads y is less than 0 they restart at 900
this.x = random(25, 475);
speedY = speedY + 0.5;
}
}
}
So far, so good. There are MANY other places where you'll have to adapt the code, but you should notice that so far you've removed more lines that You've added. That's a good thing. As long as your code is easy to read, making it shorter means that there's less places to look for nasty bugs to fix.
Also, when you avoid repeating the same lines (like all those identical Render functions) by having them all in one place (the Drawable class in this case), you also avoid having to hunt down every iteration of your code if you want to make one change. This is called DRY code. DRY (for Dont Repeat Yourself) code is waaay easier to debug and maintain. As a rule of thumb, every time you copy and paste code without any change, you should ask yourself if you could just keep these line in one centralized place, whether it's a variable or a function or a class.
I'll let you code the Burger class. I think you'll manage it now that you have seen how to deal with the others.
Now, let's take a look at how to update your main loop, draw():
void draw ()
{
// As a general rule, all your game states should be dealt in the game loop.
// I like 'switch' statements for this kind of operations
// Also, try not to clutter the game loop. If you have a lot of code here, you should probably put them into functions
// it will make it easier to read and the game loop can very easily become a spaghetti nightmare if you're not careful.
switch(gameMode) {
case Menu:
// Do Menu stuff
break;
case Active:
drawBackground(); // Maybe this should be before the switch, I'm not sure how you want to deal with this
// Updates
user1.Update();
burger.Update();
for (Salad s : salads) {
s.Update();
}
// Check for collisions
// I may be mistaken but I think only the Homer can collide with stuff
if (burger.Crash(user1.x, user1.y, user1.w, user1.h)) {
// Do burger crash stuff
}
for (Salad s : salads) {
if (s.Crash(user1.x, user1.y, user1.w, user1.h)) {
// Do Salad crash stuff
}
}
// Render
user1.Render();
burger.Render();
for (Salad s : salads) {
s.Render();
}
break;
case End:
// Do End stuff
break;
}
}
This should put you on track.
If, for some reason you only want to use the intersect method: remember that the width and height of your objects are the one you use for their images.
You probably have questions, don't hesitate to ask away. And have fun!
the function
boolean intersect(float x1, float y1, float w1, float h1, float x2, float y2, float w2,
float h2)
{
boolean checkX = x1 < x2 && x1+w1 > x2 || x1 < x2+w2 && x1+w1 > x2+w2 || x1 > x2 &&
x1+w1 < x2+w2 || x1 < x2 && x1+w1 > x2+w2;
boolean checkY = y1 < y2 && y1+h1 > y2 || y1 < y2+h2 && y1+h1 > y2+h2 || y1 > y2 &&
y1+h1 < y2+h2 || y1 < y2 && y1+h1 > y2+h2;
return checkX && checkY;
}
only checks if rect1 is inside of rect2
in the function you dont neeed any or statements
here is the correct function
boolean intersect(float x1, float y1, float w1, float h1, float x2, float y2, float, w2, float h2)
{
boolean checkX = x1 < x2+w2 && x1+w1>x2;
boolean checkY = y1 < y2+h2 && y1+h1>y2;
return checkX && checkY;
}
I'm all new to this and doing a beginner's lecture on Java (with Processing). Our assignment this time is the bouncing ball. I've (sort of) successfully gotten it to move the way it's supposed to and put it into a class, but I can't get the array right.
Here's the version using the class:
class Ball {
float x;
float y;
float ySpeed;
float gravity;
int counter = 0;
Ball()
{
x = 300;
y = 300;
ySpeed = 2.5;
gravity = 0.2;
}
void move()
{
y = y + ySpeed;
ySpeed = ySpeed + gravity;
if (y > height-25 )
{ySpeed = ySpeed * -0.85;
y = height-25;
counter++;
}
println(counter);
if(counter >= 17)
{ySpeed=0;
y=height-25;}
}
void display()
{
ellipse(x,y,50,50);
}
}
//using the class:
Ball b1;
void settings()
{
size(800,600);
}
void setup()
{
b1 = new Ball();
}
void draw()
{
background(0);
b1.move();
b1.display();
}
Here's what I ended up with after messing it up completely.
//class Ball
class Ball {
float[] x;
float[] y;
float[] ySpeed;
float[] gravity;
int i;
int counter = 0;
//constructor
Ball()
{
x[i] = 300;
y[i] = 300;
ySpeed[i] = 2.5;
gravity[i] = 0.2;
}
void move()
{
y[i] = y[i] + ySpeed[i];
ySpeed[i] = ySpeed[i] + gravity[i];
//changes direction; (-25) to avoid movement beyong boundary
if (y[i] > height-25 )
{ySpeed[i] = ySpeed[i] * -0.85;
y[i] = height-25;
}
println(counter);
if(counter >= 17)
{ySpeed[i]=0;
y[i]=height-25;}
}
void display()
{
//draw ellipse
ellipse(x[i],y[i],50,50);
}
}
//using the class
final int i = 9;
Ball[] Balle = new Ball[10];
void settings()
{
size(800,600);
}
void setup()
{
Balle[i] = new Ball();
for (int i = 0; i < Balle.length; i++)
{Balle[i] = new Ball(x[i],y[i],50,50), i*4);
}
}
I suppose this looks weird because it's picked together from several different help pages... the current error is "variable x does not exist" on
{Balle[i] = new Ball(x[i],y[i],50,50), i*4);
I'm aware there are several other problems.
Right now I'm quite lost in figuring out how it works. Could somebody give me a hint?
variable x does not exist - It's because you don't have x as a global variable, but as a class variable, which is therefore only accessible from within the Ball class or by an instance of the Ball class. I don't exactly know why you're using arrays for x and y, primitives would do just fine. And don't forget to add the draw() method, as in processing, that serves as the 'main loop', it gets executed every 0.x sec (frameRate) so you MUST use that as well. Your other functions like display() etc.. can also be called from within the draw function.
Geez, what did I even do there?
Here it is:
Ball[] balls = new Ball[10];
void settings()
{
size(600,800);
}
void setup()
{
for (int i = 0; i < balls.length; i++)
{
balls[i] = new Ball();
}
}
void draw()
{ background(0);
for (int i = 0; i < balls.length; i++)
{
balls[i].move();
balls[i].display();
}
}
Is programming like that, stumbling around in the dark until you get hit by a brick...?
Here's a pseudo code.
If ball <= bottom, reverse the speed of ball.
(That means when it hits the floor, the speed reverses. Multiply it with -1)
Other wise, speedOfBall = speed - (gravity*time);
You can easily calculate the displacement in terms of coordinates as s = velocity*time + .5*gravity*time^2.
I'm doing this bouncing ball problem and I have was given this formula: (velocity) vx = v0*cos(angle). and (x-position) x = v0*cos(angle)*t. However, I cannot get the ball to bounce properly.
The problem is that after the ball hits the right vertical wall, it starts to bounce inside certain range on the right-hand-side of the window. (y and vy shouldn't matter in this case.)
How can I fix this weird bouncing problem to make it bounce property in the x direction?
public class GamePanel2 extends JPanel implements KeyListener, ActionListener{
Timer tm = new Timer(60, this); //this refers to the ActionListener
public int score = 0;
public GamePanel2(){
addKeyListener(this);
setFocusable(true);
setBackground(Color.BLACK);
}
public int getScore() {
return score;
}
public double v0 = 100;
public double t = 0;
public double angle = Math.PI/2.5;
public double x = 0;
public double y = 0;
public double vx =0;
public double vy = 0;
public int move = 0;
public int paddlex =0;
public void paintComponent(Graphics g){
int h = getHeight();
int w = getWidth();
vx = v0*Math.cos(angle);
vy = v0*Math.sin(angle);
Graphics2D g2d = (Graphics2D)g;
g2d.translate(0.0,h);
g2d.scale(1.0, -1.0);
//ball
g2d.setColor(Color.GREEN);
g2d.fillOval((int)Math.round(x), (int)Math.round(y+6), 20, 20);
//paddle
g2d.setColor(Color.RED);
g2d.fillRect(paddlex + move, 0, 60, 6);
repaint();
}
//KeyListener methods
#Override
public void keyPressed(KeyEvent arg0) {
if(arg0.getKeyCode() == KeyEvent.VK_SPACE){
tm.start();
}
else if(arg0.getKeyCode()==KeyEvent.VK_ESCAPE){
tm.stop();
}
if(arg0.getKeyCode() == KeyEvent.VK_RIGHT){
move += 30;
}
//if pressed right key
if(arg0.getKeyCode() == KeyEvent.VK_LEFT){
move -= 30;
}
repaint();
}
#Override
public void keyReleased(KeyEvent arg0) {
}
#Override
public void keyTyped(KeyEvent arg0) {
}
#Override
public void actionPerformed(ActionEvent arg0) {
t = 0.2;
vy -= 9.8;
x += vx;
y += (vy)*t-(t*t*9.8)*0.5;
if( x<= 0){
vx = v0*Math.cos(angle);
}
if (x>=getWidth()-20){
vx =-(v0*Math.cos(angle));
}
repaint();
}
}
You're not even close. The differential equations of motion for a ball with gravity supplying the only force are
d^2x/dt^2 = -9.8 and d^2x/dt^2 = 0
You need to integrate these equations. For this purpose, you need to get rid of the second degree differentials by introducing a new variable:
dv_y/dt = -9.8 and dv_x/dt = 0
dy/dt = v_y dx/dt = v_x
With Euler forward differences (the simplest possible integration method), this becomes:
v_y[i+i] = v_y[i] + h * -9.8
y[i+1] = y[i] + h * v_y[i]
v_x[i+1] = v_x[i] + h * 0 // x-velocity is constant!
x[i+1] = x[i] + h * v_x[i]
When the ball encounters a vertical wall with a perfectly elastic collision, the x velocity instantly changes sign. When it hits the floor or ceiling, the y velocity changes sign.
Your formula provides only the initial values of v_x and v_y. All x and y values after are results of the above Euler equations. In pseudocode it will look something like this:
// Initialize the velocity components.
vx = v0 * cos(theta)
vy = v0 * sin(theta)
// Initialize the position of the ball.
x = R // in the corner of the first quadrant
y = R
// Choose a time increment.
h = < a very small number of seconds >
// Start the clock.
t = 0
while (t < END_OF_SIMULATION) {
draw_ball(x,y)
x = x + h * vx;
y = y + h * vy;
vy = vy - h * 9.8;
// Check for bounces
// Assumes box has corners (0,0), (W,H)
if ((vx < 0 and x < r) or (vx > 0 && x > W-r)) x = -x;
if ((vy < 0 and y < r) or (vy > 0 && y > H-r)) y = -y;
t = t + h
}
Note that that 9.8 means that the units are meters and seconds. You need to scale pixels in the Java window and use a timer to get a realistic result.
To roughly simulate lossy collision, you can steal some velocity on every bounce:
x = -<a number a bit less than 1.0> * x and
y = -<a number a bit less than 1.0> * y
With these, the ball will slow down a bit every time it hits a wall.
I can't find where you're changing the angle after detecting a bounce. I also don't see bounds checking for all four sides of the windows the ball is in.
There's a related bug you might run into where there's a double bounce in a corner that leaves the ball outside the window after all the calculations are done. Think about ways to handle that case.
Ok so I have been experimenting with java for a few weeks now, following both in class, and online tutorials. I made a simple game where squares fall towards the bottom of the screen, while the player controls a small ball, only moving on the x-axis and trys to avoid them.
The problem that I am having is that the squares start out falling too fast. Right now I have them set as follows:
ix = 0;
iy = 1;
Then in my move() method, I have the following:
hitbox.x += ix;
hitbox.y += iy;
In this example, ix and iy are both integers.
My first assumption was to change the ints to floats, then use:
ix= 0;
iy = 0.5;
and then:
hitbox.x += ix;
hitbox.y += 0.5f;
But this just freezes the objects in their tracks . I believe that this is because cords are taken as integers, so I figured that if I modified my getX() and getY() methods, maybe I could manipulate them somehow to use decimal numbers? But I am not quite sure how to. Any help/hints/solutions to this problem would be Greatly appreciated.
Here is some revelent code, let me know if anymore is needed!
Enemy Manager:
public class EnemyManager {
private int amount;
private List<Enemy> enemies = new ArrayList<Enemy>();
private GameInJavaOne instance;
public EnemyManager(GameInJavaOne instance, int a){
this.amount = a;
this.instance = instance;
spawn();
}
private void spawn(){
Random random = new Random();
int ss = enemies.size();
// If the current amount of enemies is less than the desired amount, we spawn more enemies.
if(ss < amount){
for(int i = 0; i < amount - ss; i++){
enemies.add(new Enemy(instance, random.nextInt(778), random.nextInt(100)+1));
}
// If its greater than the desired number of enemies, remove them.
}else if (ss > 20){
for(int i = 0; i < ss - amount; i++){
enemies.remove(i);
}
}
}
public void draw(Graphics g){
update();
for(Enemy e : enemies) e.draw(g);
}
private void update() {
boolean re = false;
for(int i = 0; i < enemies.size(); i ++){
if(enemies.get(i).isDead()){
enemies.remove(i);
re = true;
}
}
if(re) spawn();
}
public boolean isColliding(Rectangle hitbox){
boolean c =false;
for(int i = 0; i < enemies.size(); i ++){
if(hitbox.intersects(enemies.get(i).getHitbox())) c = true;
}
return c;
}
}
Entity:
public abstract class Entity {
protected int x, y, w, h;
protected boolean removed = false;
public Entity(int x, int y){
this.x = x;
this.y = y;
}
public void Draw(Graphics g){
}
public int getX() { return x; }
public int getY() { return y; }
public int getH() { return h; }
public int getW() { return w; }
}
and the enemy class:
public class Enemy extends Entity{
private Rectangle hitbox;
private int ix, iy;
private boolean dead = false;
private GameInJavaOne instance;
public Enemy(GameInJavaOne instance, int x, int y){
super(x, y);
this.instance = instance;
hitbox = new Rectangle(x, y, 32, 32);
ix = 0;
iy = 1;
}
private void move(){
if(instance.getStage().isCollided(hitbox)){
iy =0;
dead = true;
}
hitbox.x += ix;
hitbox.y += iy;
}
public boolean isDead() {return dead;}
public Rectangle getHitbox() {return hitbox; }
public void draw(Graphics g){
move();
g.setColor(Color.MAGENTA);
g.fillRect(hitbox.x, hitbox.y, hitbox.height, hitbox.width);
}
}
You are using a Rectangle class to represent the position of your box (even though you call it the hitbox), Rectangle does indeed have members x and y which are integers and so when you call
rectangle.x+=0.5f;
What you are really calling is rectangle.x+=(int)0.5f; and (int)0.5f==0.
The Rectangle class is simply inappropriate for holding the position of the box if you want float precision. Consider holding the box's real position as a double or float and casting to int to render it.
So your rendering code would become;
g.fillRect((int)positionX,(int)positionY, hitbox.height, hitbox.width);
where positionX and positionY are doubles. (You could also use Vector2d if you'd prefer to keep x and y together)
Other points
You seem to be extending an Entity class with x,y,w and h and yet never use them, this seems dangerous, why are you extending Entity but recreating your own positional code.
Your game loop isn't shown, however, I can see that you hard code the change in x and y. This is presumably because in your game loop you 'ask for' some frame speed, say 60fps and assume you'll get it. This works fine on a resource rich system, but as soon as you have any resource shortage you will start getting frames that are shorter than 60fps. In most games you don't even notice this because it just makes a larger jump to compensate but here you assume 60fps. It is wise to get an actual frame time and multiply that by a velocity to get you change in x and y.