I have a moving image as a background
PImage background;
int x=0; //global variable background location
rocket Rocket;
void setup(){
size(800,400);
background = loadImage("spaceBackground.jpg");
background.resize(width,height);
Rocket = new rocket();
}
void draw ()
{
image(background, x, 0); //draw background twice adjacent
image(background, x+background.width, 0);
x -=4;
if(x == -background.width)
x=0; //wrap background
Rocket.defender();
Rocket.move();
}
In a different class i'm trying to make a rocket move up and down
class rocket {
float x;
float y;
float speedy;
boolean up;
boolean down;
rocket(){
x = 50;
y = 200;
speedy = 3;
}
void move() {
if(up)
{
y = y - speedy;
}
if(down)
{
y = y + speedy;
}
}
void defender(){
fill(255,0,0);
rect(x,y,50,20);
triangle(x+50,y,x+50,y+20,x+60,y+10);
fill(0,0,100);
rect(x,y-10,20,10);
}
void keyPressed(){
if(keyCode == UP)
{
up = true;
}
if(keyCode == DOWN)
{
down = true;
}
}
void keyReleased(){
if(keyCode == UP)
{
up = false;
}
if(keyCode == DOWN)
{
down = false;
}
}
}
The rocket will display but won't move. I tried everything I know but nothing works. I also tried the rocket class just as a project by itself and the rocket moves, so it has to be something with the class. i'm quite new to coding so please keep that in mind, thank you in advance.
The keyPressed() and keyReleased() functions (and any other event function) need to be at the sketch level, not inside another class. If they're inside another class, Processing doesn't know how to find them.
So, what you need to do is move the keyPressed() and keyReleased() functions to the sketch, and then call functions on your Rocket class (class names should start with an upper-case letter, btw), similar to how you're calling rocket.defender() and rocket.move() (variable names should start with a lower-case letter) from the sketch-level draw() function.
Related
class Bullet {
float bulletX, bulletY;
float angle;
int x;
int y;
int score; // add a score variable
static final float BULLET_SPEED = 5; // define a constant for the bullet's speed
Bullet(float x, float y, float angle) {
this.bulletX = x;
this.bulletY = y;
this.angle = angle;
}
// Updates the position of the bullet based on its angle and speed.
void update() {
bulletX += cos(angle) * BULLET_SPEED;
bulletY += sin(angle) * BULLET_SPEED;
}
// Draws the bullet image on the screen.
void show() {
drawBullet();
}
// Draws the bullet image on the screen.
void drawBullet() {
image(Bulletimg, bulletX, bulletY);
Bulletimg.resize(30, 30);
}
//Returns true if the bullet is off screen, false otherwise.
boolean offScreen() {
return bulletX < 0 || bulletX > width || bulletY < 0 || bulletY > height;
}
//Checks if the bullet hits the enemy, and updates the score and enemy position accordingly.
// check for collision
void checkCollision(Enemy e) {
float distance = dist(bulletX, bulletY, e.x, e.y);
if (distance < e.x / 2) {
// assuming enemy.size is the radius of the
}
}
}
I tried changing around the check collision(enemy e) block and I'm not sure how i would go about removing an enemy object and also updating my score. i've tried messing about with the draw(); method but i cant seem to figure it out without breaking my entire game. any help with this class would be much appreciated.
You can use/create some attribute in your Enemy object to know/check if is alive or death.
For example in your check collision you can add
if (distance < e.x / 2) {
// assuming enemy.size is the radius of the
e.alive = false
}
Edit: I dont know how your manage the Enemy object and if it can be modified directly in the check collision method if this is not possible then you need to find a way to have access inside the method or use a return and manage that return outside.
Me and my partner are attempting to create the game Pong for our computer science final project. We created a reference code where 2 cubes can be controlled upwards and downwards and it works fine. The problem occurs when attempting to control both cubes at the same time (only 1 cube will move at a time). We want to make both cubes move at the same time.
WE want to say that:
yPos - is the y position of the black cube
xPos - is the x position of the black cube
xPos2 - is the x position of the blue cube
YPos2 - is the y position of the blue cube
Keys:
A - Go up for black cube
Z - Go down for black cube
K - Go up for blue cube
M - go down for blue cube
We have tried using a more complicated version which used j-label animation. How ever we want to make our pong game through the graphics function. But we do not understand:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class PongHelpNeed extends JFrame implements KeyListener
{
// booleans to tell which key is pressed
boolean upKey;
boolean downKey;
boolean upKey2;
boolean downKey2;
// the position variables
int yPos;
int xPos;
int xPos2;
int yPos2;
public PongHelpNeed ()
{
//create window
super ("Controller");
setSize (660, 700);
// set keys to false and original positions
upKey = false;
downKey = false;
upKey2 = false;
downKey2 = false;
xPos = 100;
yPos = 350;
xPos2 = 500;
yPos2 = 350;
// add the frame as a listener to your keys
addKeyListener (this);
// Show the frame
setVisible(true);
}
//needs to be here because the class implements KeyListener
public void keyTyped (KeyEvent e)
{
System.out.println (e.getKeyCode () + " Typed");
}
//needs to be here because the class implements KeyListener
public void keyPressed (KeyEvent e) {
//check if keys a,z or k,m are pressed
if (e.getKeyCode () == KeyEvent.VK_A)
{
upKey = true;
}
else if (e.getKeyCode () == KeyEvent.VK_Z)
{
downKey = true;
}
else if (e.getKeyCode () == KeyEvent.VK_K)
{
upKey2 = true;
}
else if (e.getKeyCode () == KeyEvent.VK_M)
{
downKey2 = true;
}
//repaint the window everytime you press a key
repaint ();
}
//needs to be here because the class implements KeyListener
public void keyReleased (KeyEvent e)
{
System.out.println (e.getKeyCode () + " Released");
}
//paints the pictures
public void paint (Graphics g)
{
//set background
g.setColor(Color.WHITE);
g.fillRect(0, 0, 660, 700);
//cube 1
g.setColor(Color.BLACK);
g.fillRect(xPos,yPos,50, 50);
//draw cube 2
g.setColor(Color.BLUE);
g.fillRect(xPos2,yPos2, 50, 50);
//if keys are pressed move the cubes accordingly up or down
if (upKey == true)
{
yPos = yPos - 15;
upKey = false;
}
else if (downKey == true)
{
yPos = yPos + 15;
downKey = false;
}
else if (downKey2 == true){
yPos2 = yPos2 + 15;
downKey2 = false;
}
else if (upKey2 == true) {
yPos2 = yPos2 - 15;
upKey2 = false;
}
}
public static void main (String[] args)
{
new PongHelpNeed ();
}
}
Our expected results are we are trying to move both cube at the same time. So when we press the A key and the K key the black square should move and the blue cube should move.
Calling repaint() does not trigger a call to the paint immediately, so it's possible that the keyPressed is triggered twice (or more) before paint.
In your paint method you are checking the keys in if-else, which means that if one of the flags is true, the rest are not checked. You also have a race condition where the keyPressed is fighting with paint over the flags. Also, if you press a key quickly multiple times, you'll lose all the extra key presses between the first handled event and the next repaint.
Instead of doing the move within paint, you should do it within the keyPressed handler. Don't set a flag to e.g. upKey = true;, but instead do the action directly: yPos = yPos - 15;. The paint method will then just refresh the view to reflect the current (updated) state.
I understand the basis of collision detection and have developed my way (as far as I know) for collision detection. However, it does not seem to be working. What I have done is instead of drawing full rectangles around sprites, shapes, and other objects, I simply made methods that draw lines (very thin rectangles) on all sides of the object, left, right, top, and bottom.
The methods that draw the thin rectangles on the left,right,top, and bottom of the specified sprites. This is probably not the best way to do collision, but this is what I have, and am open to all ideas and different solutions!
Note: The(int)(x-Game.getCamera().getX()),(int)(y + height -Game.getCamera().getY()), is simply for the camera, so when the player moves, the trees (in my case the object I want to collide with) do not move with him
public Rectangle getBounds() {
return new Rectangle((int)(x-Game.getCamera().getX()),
(int)(y + height - Game.getCamera().getY()),width,height-height);
}
public Rectangle getBoundsTop() {
return new Rectangle((int)(x-Game.getCamera().getX()),
(int)(y- Game.getCamera().getY()),width,height-height);
}
public Rectangle getBoundsRight() {
return new Rectangle((int)(x + width -Game.getCamera().getX()),
(int)(y - Game.getCamera().getY()),width - width,height);
}
public Rectangle getBoundsLeft() {
return new Rectangle((int)(x -Game.getCamera().getX()),
(int)(y- Game.getCamera().getY()),width - width,height);
}
Actual collision CHECKING (in player class)-
if(getBounds().intersects(treeTile.getBoundsTop())) {
//What happens when they collide
//When the bottom of the player collides with the top of the tree.
}
if(getBoundsTop().intersects(treeTile.getBounds())) {
//What happens when they collide
//When the top of the player collides with the bottom of the tree
}
if(getBoundsRight().intersects(treeTile.getBoundsLeft())) {
//What happens when they collide
//when the right side of the player collides with the left of the
//tree
}
if(getBoundsLeft().intersects(treeTile.getBoundsRight())) {
//What happens when they collide
//When the left of the player collides with the right of the tree
}
I appreciate all the help I can get
Here is collision and movement code-
for (int i = 0; i < handler.object.size(); i++) {
Square handle = handler.object.get(i);
if (getBounds().intersects(treeTile.getBoundsTop())) {
handle.setvelY(-1);
}
if (getBoundsTop().intersects(treeTile.getBounds())) {
handle.setvelY(0);
}
if (getBoundsRight().intersects(treeTile.getBoundsLeft())) {
handle.setvelX(0);
}
if (getBoundsLeft().intersects(treeTile.getBoundsRight())) {
handle.setvelX(0);
}
}
Movement-
public void keyPressed(KeyEvent e) {
int code = e.getKeyCode();
for (int i = 0; i < handler.object.size(); i++) {
Square handle = handler.object.get(i);
if (handle.getId() == ObjectId.Zelda) {
if (code == KeyEvent.VK_D) {
handle.right();
}
if (code == KeyEvent.VK_A) {
handle.left();
}
if (code == KeyEvent.VK_W) {
handle.up();
}
if (code == KeyEvent.VK_S) {
handle.down();
}
}
My new collision idea -
boolean walkRight = true;
boolean walkLeft = true;
boolean walkDown = true;
boolean walkUp = true;
public void tick() {
if(walkRight == true) {
velX = 2;
}if(walkLeft == true) {
velX = -2;
}if(walkDown == true) {
velY = 2;
}if(walkUp == true) {
velY = -2;
}
if (getBounds().intersects(treeTile.getBoundsTop())) {
walkDown = false;
}
if (getBoundsTop().intersects(treeTile.getBounds())) {
walkUp = false;
}
if (getBoundsRight().intersects(treeTile.getBoundsLeft())) {
walkRight = false;
}
if (getBoundsLeft().intersects(treeTile.getBoundsRight())) {
walkLeft = false;
}
Something like this, not exactly, it is just an example.
Have you tried using 1 instead of width - width and height - height ?
I think these evaluating to 0 for the width / height is causing the intersects function to fail.
EDIT
I think you're over complicating this. If you just have one big collision box, instead of four small ones, then where ever you're moving your player, you can
// Square previousPosition = currentPosition
// do move player code, which presumably updates the currentPosition
// loop through all the trees you have
// if the player is colliding with a tree
// currentPosition = previousPosition
This should handle the player colliding with any side of the tree, since we just move them back to where they were previously.
I have a class which spawns an enemy, and a class that spawns a player. At the moment they are both 2 circles coming towards each other. I have made a collision detection function for when they crash, but I can't make it work. I have made the function outside the classes and try to call the position variables of each class, but it says I can't make a static reference to a non static field. I have also tried the collision detection in each class which also doesn't work.
class Player {
int Pos_X;
int Pos_Y;
int Speed;
Player(int x, int y, int speed) {
this.Pos_X = x;
this.Pos_Y = y;
this.Speed = speed;
}
void Update() {
ellipse(Pos_X, Pos_Y, 40, 40);
Pos_X += Speed;
}
}
class Enemy {
int Pos_X;
int Pos_Y;
int Speed;
Enemy(int x, int y, int speed) {
this.Pos_X = x;
this.Pos_Y = y;
this.Speed = speed;
}
void Update() {
ellipse(Pos_X, Pos_Y, 40, 40);
Pos_X -= Speed;
}
}
Player Player1;
Enemy Enemy1;
void setup() {
size (500, 500);
Player1 = new Player (0, 200, 3);
Enemy1 = new Enemy (500, 200, 3);
}
void draw() {
background(200);
Player1.Update();
Enemy1.Update();
if (intersectsBox(Player.Pos_X, Player.Pos_Y)) {
ellipse(100, 100, 100, 100);
}
}
boolean intersectsBox(float X, float Y) {
if (X > Enemy.Pos_X && X < Enemy.Pos_X + 40) {
if (Y > Enemy.Pos_Y && Y < Enemy.Pos_Y + 40) {
return true;
}
}
}
To use a variable that's in a class, you have to refer to an instance of that class. In your code, Enemy is a class, and Enemy1 is an instance of that class. So when you try to do this:
if (X > Enemy.Pos_X && X < Enemy.Pos_X + 40) {
Processing gives you an error because you're using the class, not an instance. Processing doesn't know which Enemy you're talking about. Instead, you have to do something like this:
if (X > Enemy1.Pos_X && X < Enemy1.Pos_X + 40) {
Now Processing knows which instance of the Enemy class you're talking about. You might also pass in an instance of Enemy as a parameter to that function, that way you can use it to collide with multiple enemies.
And just a general piece of advice: your code would be much easier to read if you followed standard formatting and naming conventions- indent your code (Processing will do it for you if you press ctrl+t in the editor), and make sure only classes start with an upper-case letter. Methods and variables should start with lower-case letters.
So I understand that I'm not coding this the best way possible at the moment; this is a sort of test run. What I'm trying to do is wall collisions using rectangles and the intersects property (sorry if I'm not using the correct terminology). So far I have 2 rectangles on screen. 1 the player controls and the other which the play is colliding with. When they collide the player stops moving. The problem is that if the player is trying to move into the rectangle while they are already colliding then the player can't move in any direction perpendicular to the movement ie if the player is holding the right arrow key moving into the rectangle, then they cannot move up or down. The game works on the premise that if your x or y coordinates aren't valid, then you will be moved back to the last valid coordinate recorded but I'm having trouble detecting the valid x and y coordinate separately. Here is the code:
public void Collision()
{
if(x < 0)
x = 0;
if(x > 400 - width)
x = 400 - width;
if(y < 0)
y = 0;
if(y > 300 - height)
y = 300 - height;
rect1 = new Rectangle(x, y, 16, 16);
rect2 = new Rectangle(sx, sy, wid, hei);
if(!rect1.intersects(rect2))
{
validX = true;
validY = true;
}
else
{
validX = false;
validY = false;
}
if(validX)
{
lastValidX = x;
}
if(validY)
{
lastValidY = y;
}
if(!validX)
{
x = lastValidX;
}
if(!validY)
{
y = lastValidY;
}
}
The Collision() method in the Guy class is where I'm having the trouble I believe. Yes my code is pretty messy right now but this is only a test.
Thanks, David.
You can implement what you're describing by doing extra logic around here (i.e. detecting cases when one is false and the other is true):
if(!rect1.intersects(rect2))
{
validX = true;
validY = true;
}
else
{
validX = false;
validY = false;
}
However, it seems like maybe you shouldn't be allowing the rectangles to ever be in a "colliding" state in the first place. For example, you can change the Move method to do something like
public void Move()
{
int oldX = x, oldY = y;
x += dx;
y += dy;
if (Collision()) {
x = oldX;
y = oldY;
}
}