Help with movement and shooting
in
Programming Questions
•
1 year ago
Hey, I'm making a small shooting-game. I have right now an ellipse which you can move with the arrowkeys from left to right and i have made a bullet which fires when you press a key. But my problem now is that i want the bullet to fire from the same position that my ellipse has. Right now the bullet only fires from the centre of the screen. How can I make the bullet (shot class) follow the ellipse's movement?
Thanks in advance!
My code:
Thanks in advance!
My code:
- //variables
ball myBall;
shot myShot;
ArrayList enemies;
void setup()
{
//size and shit
size(400, 400);
frameRate(60);
smooth();
//declare new instances of the classes
myBall = new ball(200, 300);
myShot = new shot(200, 300);
enemies = new ArrayList();
}
void draw()
{
background(0);
//run the classes
myBall.run();
myShot.displayShot();
enemies.add(new enemies1());
//add enemies
for (int i = enemies.size()-1; i>= 0; i--)
{
enemies1 e = (enemies1) enemies.get(i);
e.displayEnemies();
}
//remove enemies
if (enemies.size() > height)
{
enemies.remove(0);
}
} - class ball {
//Variables
float xPos;
float yPos;
float sizeH = 50;
float sizeW = 50;
float speed = 3;
float rightWall = 375;
float leftWall = 25;
float gravY = random(-1, 1);
//constructor
ball (float _xPos, float _yPos)
{
xPos = _xPos;
yPos = _yPos;
}
//run everything in one method in first_game class
void run()
{
display();
movement();
rightArrow();
leftArrow();
}
//display the ball
void display()
{
ellipse(xPos, yPos, sizeH, sizeW); //draw ellipse
strokeWeight(2);
}
//move the ball
void movement()
{
if (xPos >= rightWall) // bounce right
{
xPos = rightWall;
}
if (xPos <= leftWall) // bounce left
{
xPos = leftWall;
}
}
//keyPressed right
void rightArrow()
{
if (keyPressed)
{
if (key == CODED)
{
if (keyCode == RIGHT) // move right
{
xPos = xPos + speed;
}
}
}
}
//keyPressed left
void leftArrow()
{
if (keyPressed)
{
if (key == CODED)
{
if (keyCode == LEFT) // move left
{
xPos = xPos - speed;
}
}
}
}
} - class shot {
//variables
float xPos;
float yPos;
float speed = 5;
boolean keys = false;
//constructor
shot(float _xPos, float _yPos)
{
xPos = _xPos;
yPos = _yPos;
}
//run everything in one method in first_game class
void displayShot()
{
//movement();
display();
space();
}
//display shot, make the shot go
void display()
{
if (keys == true)
{
rect(xPos, yPos, 5, 10);
yPos = yPos - speed;
}
else
{
keys = false;
}
}
void space()
{
if (keyPressed)
{
if (key == 'k' || key == 'K' && keys == false) // move right
{
keys = true;
}
}
}
void keyReleased()
{
if (key =='k'|| key == 'K' && keys == true)
{
//keys = false;
}
}
}
1