i've got an issue with my breakout game in java. Everything works well other than my paddle going off the screen on the right side, my ball does this too, but not worried about that right now.
// prevent paddle from moving outside of the screen
Public void update() {
x += xVelocity;
if (x <= 0) {
setX(0);
xVelocity = -1;
}
if (x >=
(Settings.WINDOW_WIDTH
- Settings.PADDLE_WIDTH) {
setX(Settings.WINDOW_HEIGHT
- Settings.PADDLE_HEIGHT);
xVelocity = 1;
}
// set velocity depending on pressing left or right
Public void keyPressed(KeyEvent e)
if (e.getKeyCode() ==
KeyEvent.VK_LEFT) {
paddle.setXVelocity(-1);
} else if (e.getKeyCode() ==
KeyEvent.VK_RIGHT) {
paddle.setXVelocity(1);
}
}
// set velocity after keys released
Public void keyReleased(KeyEvent e)
if (e.getKeyCode() ==
KeyEvent.VK_LEFT) {
paddle.setXVelocity(0);
} else if (e.getKeyCode() ==
KeyEvent.VK_RIGHT) {
paddle.setXVelocity(0);
}
}
How do i get the paddle to
stay on screen on the right
side?
Any help appreciated
Change this
if (x <= 0) {
setX(0);
xVelocity = -1;
}
if (x >=
(Settings.WINDOW_WIDTH
- Settings.PADDLE_WIDTH) {
setX(Settings.WINDOW_HEIGHT
- Settings.PADDLE_HEIGHT);
xVelocity = 1;
}
to this
if (x <= 0) {
setX(0);
xVelocity = -1;
}
if (x >= (Settings.WINDOW_WIDTH - Settings.PADDLE_WIDTH) {
setX(Settings.WINDOW_WIDTH - Settings.PADDLE_WIDTH);
xVelocity = 1;
}
When you check if the value of x is within the difference of window width and paddle width, the new value of x should be set as the difference of window width and paddle width, NOT the difference between window height and paddle height.
Related
I want the ball.move(); function in the code below to continue running after pressing space once. It only works if I continue pressing the space key.
void draw() {
if (start == true) {ball.move();}
}
void keyPressed() {
if (key == ' '){start = true;}
}
void keyReleased() {
if (key == ' ') {start = false;}
}
It's for a Pong game I am making and each time the ball hits the edge it is teleported to the center of the canvas. That´s when I want to be able to start the ball movement manually again.
Here is the whole code:
Ball ball;
Player player1;
Player player2;
int scorePlayer1 = 0;
int scorePlayer2 = 0;
PFont font;
boolean start;
void setup() {
size(1368,768);
frameRate(144);
noStroke();
ball = new Ball(width/2, height/2, 30);
player1 = new Player(15, height/2, 30, 150);
player2 = new Player(width-15, height/2, 30, 150);
ball.speedX = 10;
}
void draw() {
background(0);
textSize(40);
textAlign(CENTER);
font = loadFont("Arial-Black-48.vlw");
textFont(font);
ball.display();
if (start == true) {ball.move();}
player1.run();
player2.run();
//Score
if (ball.left() < 0) {
scorePlayer2 = scorePlayer2 + 1;
ball.x = width/2;
ball.y = height/2;
}
if (ball.right() > width) {
scorePlayer1 = scorePlayer1 +1;
ball.x = width/2;
ball.y = height/2;
}
text(scorePlayer1, width/2-75, 50);
text(scorePlayer2, width/2+75, 50);
//Collision
if (ball.top() < 0) {
ball.speedY = -ball.speedY;
}
if (ball.bottom() > height) {
ball.speedY = -ball.speedY;
}
if (ball.left() < player1.right() && ball.y > player1.top()-10 && ball.y < player1.bottom()+10) {
ball.speedX = -ball.speedX;
ball.speedY = map(ball.y - player1.y, -player1.h/2, player1.h/2, -5, 5);
}
if (ball.right() > player2.left() && ball.y > player2.top()-10 && ball.y < player2.bottom()+10) {
ball.speedX = -ball.speedX;
ball.speedY = map(ball.y - player2.y, -player2.h/2, player2.h/2, -5, 5);
}
if (player1.bottom() > height) {
player1.y = height-player1.h/2;
}
if (player1.top() < 0) {
player1.y = player1.h/2;
}
if (player2.bottom() > height) {
player2.y = height-player1.h/2;
}
if (player2.top() < 0) {
player2.y = player1.h/2;
}
}
//Movement
void keyPressed() {
player1.pressed((key == 'w' || key == 'W'), (key == 's' || key == 'S'));
player2.pressed((keyCode == UP), (keyCode == DOWN));
if (key == ' '){start = true;}
}
void keyReleased() {
player1.released((key == 'w' || key == 'W'), (key == 's' || key == 'S'));
player2.released((keyCode == UP), (keyCode == DOWN));
if (key == ' ') {start = false;}
}
class Ball {
float x;
float y;
float d;
float speedX;
float speedY;
color c;
//Constructor
Ball(float tempX, float tempY, float tempD){
x = tempX;
y = tempY;
d = tempD;
speedX = 0;
speedY = 0;
c = (255);
}
void display() {
fill(c);
ellipse(x,y,d,d);
}
void move() {
x = x + speedX;
y = y + speedY;
}
//Collision help
float top() {
return y-d/2;
}
float bottom() {
return y+d/2;
}
float left() {
return x-d/2;
}
float right() {
return x+d/2;
}
}
class Player {
float x, y;
float w, h;
float speedY = 0.0;
color c;
boolean moveUp = false, moveDown = false;
//Constructor
Player(float tempX, float tempY, float tempW, float tempH){
x = tempX;
y = tempY;
w = tempW;
h = tempH;
speedY = 0;
c = (255);
}
void run() {
display();
move();
}
void display() {
fill(c);
rect(x-w/2, y-h/2, w, h);
}
//Movement
void move() {
if (!moveUp && !moveDown) {speedY = speedY * 0.85;}
if (moveUp) {speedY -= 1;}
if (moveDown) {speedY += 1;}
speedY = max(-7.0, min(7.0, speedY));
y += speedY;
}
void pressed(boolean up, boolean down) {
if (up) {moveUp = true;}
if (down) {moveDown = true;}
}
void released(boolean up, boolean down) {
if (up) {moveUp = false;}
if (down) {moveDown = false;}
}
//Collision help
float top() {
return y-h/2;
}
float bottom() {
return y+h/2;
}
float left() {
return x-w/2;
}
float right() {
return x+w/2;
}
}
In the code below, you are setting start to true when the key is pressed and false when the press is done. You can simply remove the line that sets start to false when the key press is done and the ball will always move when the space is pressed.
//Movement
void keyPressed() {
player1.pressed((key == 'w' || key == 'W'), (key == 's' || key == 'S'));
player2.pressed((keyCode == UP), (keyCode == DOWN));
if (key == ' '){start = true;}
}
void keyReleased() {
player1.released((key == 'w' || key == 'W'), (key == 's' || key == 'S'));
player2.released((keyCode == UP), (keyCode == DOWN));
//if (key == ' ') {start = false;}
}
I suppose you want the ball to stop moving when space is pressed again. This can be done in your keyPressed method as well by toggling start instead of setting it to true. Something like if (key == ' '){start = !start;}
Your problem is that when you release the space bar, it sets the start field to false. Then when the next draw() method is called, it sees that start==false and so doesn't move the ball.
If you remove that line from the keyReleased method, then it should run correctly?
I have a program to move a square about using the keyboard. It moves around fine when I press one of the arrow keys, but if I move it to the edge of the frame, I want it to stop. It does not do this however. If I move the square to the edge of the frame it keeps going and moves right past the edge of the screen.
I have put controls into my code to try stopping the square, but they don't seem to be working. Not really sure what is going wrong here.
This is the code to set up and draw the square:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
#SuppressWarnings("serial")
public class MovingSquare extends JPanel implements ActionListener, KeyListener
{
// We need a timer to move the shape
Timer shapeTimer = new Timer(5, this);
// X and Y coordinates of square (top left corner), and the factors by which it will move or resize each time
double xPos = 0, yPos = 0, movementX = 0, movementY = 0;
// Size of the square
int squareSize = 40;
// Width and height of the parent frame
int windowWidth;
int windowHeight;
// Movement bounds of the square
// These will prevent it from being moved off the edge of the frame
int xBound;
int yBound;
// Constructor method for our class
public MovingSquare(int w, int h) // Constructor is passed the size of the parent frame
{
// Start the timer
shapeTimer.start();
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
windowWidth = w;
windowHeight = h;
xBound = (windowWidth - squareSize);
yBound = (windowHeight - squareSize);
}
// This is where the fun starts! Painting the graphics object
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
// Create a new rectangle (which is actually a square!)
Rectangle2D movableSquare = new Rectangle2D.Double(xPos, yPos, squareSize, squareSize);
// Draw the above square on the graphics object
g2.draw(movableSquare);
}
public void actionPerformed(ActionEvent e)
{
// Redraw the square when something happens
repaint();
// Set the new x and y coordinates, depending on which direction we have moved
xPos += movementX;
yPos += movementY;
}
public void moveUp()
{
// Check to see if the shape is already at the top edge of the screen
if (yPos == 0)
{
movementY = 0;
movementX = 0;
}
// Set the movement factor - negative Y because we are moving UP!
movementY = -0.5;
movementX = 0;
}
public void moveDown()
{
// Check to see if the shape is already at the bottom edge of the screen - specified by the X and Y bounds
if (yPos == yBound)
{
movementY = 0;
movementX = 0;
}
// Set the movement factor - positive Y because we are moving DOWN!
movementY = 0.5;
movementX = 0;
}
public void moveLeft()
{
// Check to see if the shape is already at the left hand edge of the screen
if (xPos == 0)
{
movementY = 0;
movementX = 0;
}
// Set the movement factor - negative X because we are moving LEFT!
movementX = -0.5;
movementY = 0;
}
public void moveRight()
{
// Check to see if the shape is already at the right hand edge of the screen - specified by the X and Y bounds
if (xPos == xBound)
{
movementY = 0;
movementX = 0;
}
// Set the movement factor - positive X because we are moving RIGHT!
movementX = 0.5;
movementY = 0;
}
public void enlargeSquare()
{
// Make the square larger
squareSize++;
}
public void shrinkSquare()
{
// Make the square smaller
squareSize--;
}
public void keyPressed(KeyEvent e)
{
// Get the Key Code of the key that has been pressed
int keyCode = e.getKeyCode();
// If the up key has been pressed
if (keyCode == KeyEvent.VK_UP)
{
// Move shape up
moveUp();
}
// If the down key has been pressed
if (keyCode == KeyEvent.VK_DOWN)
{
// Move shape down
moveDown();
}
// If the right key is pressed
if (keyCode == KeyEvent.VK_RIGHT)
{
// Move shape right
moveRight();
}
// If the left key is pressed
if (keyCode == KeyEvent.VK_LEFT)
{
// Move shape left
moveLeft();
}
// If the left brace key is pressed
if (keyCode == KeyEvent.VK_OPEN_BRACKET)
{
shrinkSquare();
}
// If the right brace key is pressed
if (keyCode == KeyEvent.VK_CLOSE_BRACKET)
{
enlargeSquare();
}
}
public void keyTyped(KeyEvent e)
{
}
public void keyReleased(KeyEvent e)
{
// Get the Key Code of the key that has been released
int keyCode = e.getKeyCode();
// If the down key was released
if (keyCode == KeyEvent.VK_UP)
{
movementX = 0;
movementY = 0;
}
// If the down key was released
if (keyCode == KeyEvent.VK_DOWN)
{
movementX = 0;
movementY = 0;
}
// If the right key was released
if (keyCode == KeyEvent.VK_RIGHT)
{
movementX = 0;
movementY = 0;
}
// If the left key was released
if (keyCode == KeyEvent.VK_UP)
{
movementX = 0;
movementY = 0;
}
}
}
And this is the main class:
import javax.swing.JFrame;
public class Square
{
public static void main(String args[])
{
// Set width and height of frame
int frameWidth = 1024;
int frameHeight = 768;
// Create new frame and set size
JFrame frmMain = new JFrame();
frmMain.setSize(frameWidth, frameHeight);
// Create a moving square and add to the frame
MovingSquare mySquare = new MovingSquare(frameWidth, frameHeight);
frmMain.add(mySquare);
// Final configuration settings for frame.
frmMain.setVisible(true);
frmMain.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmMain.setTitle("Moving Square");
}
}
You actionPerformed method is updating the position of your square, well beyond what your moveXxx methods are, you should do your range checking there
#Override
public void actionPerformed(ActionEvent e)
{
// Set the new x and y coordinates, depending on which direction we have moved
xPos += movementX;
yPos += movementY;
if (xPos < 0) {
xPos = 0;
} else if (xPos + squareSize > xBound) {
xPos = xBound - squareSize;
}
if (yPos < 0) {
yPos = 0;
} else if (yPos + squareSize > yBound) {
yPos = yBound - squareSize;
}
// Redraw the square when something happens
repaint();
}
If you know the width and height of ths screen and the rect, you can easiely check if it's inside:
int fX0 = 0, // left x border
fX1 = frameWidth, // right x border
fY0 = 0, // top y border
fY1 = frameHeight; // bottom y border
int rX0, rX1, rY0, rY1; // keep these values updated width the rectangles position:
//rX0 = rectangle position x
//rX1 = rectangle position x + rectangle width
//rY0 = rectangle position y
//rY1 = rectangle position y + rectangle height
// Then, to check if the rect is inside the frame:
if (
rX0 >= fX0 &&
rX1 < fX1 &&
rY0 >= fY0 &&
rY1 < fY1
) { /* the rectangle is inside the frame bounds */ }
else { /* it's not inside the bounds, e.g. cancel movement */ }
The second method of doing this is by using the Rectangle class (from awt I think):
Rectangle f = new Rectangle(0, 0, frameWidth, frameHeight); // bounds of the frame
Rectangle r = new Rectangle(...); // Your square bounds
// To check if r is inside f
if (
f.contains(r)
) { /* the rectangle is inside the frame bounds */ }
else { /* it's not inside the bounds, e.g. cancel movement */ }
You can make an extra method:
public boolean Check(){
if(xPos >0 && xPos-squareSize<frameWidth && yPos>0 && yPos-squareSize<frameHeight){
//use a flag for example and make it false
}else
//flag==true
return flag;
}
Into KeyEvent method(if flag==true) then do the movement else do nothing or reset the xpos and ypos coordinates back to default or to a specific position of the JFrame.
Also it is easy to add an If(into KeyEvent methods)statement to check the coordinates and if they are accepted then do the movement.
For example:
public void KeyPressed(KeyEvent key){
if(Check()==true){
..........//the code you have into KeyPressed method
}
}//end of method KeyPressed
I am developing a two player game in Processing (running on Java). One user will control his character using the WASD keys and the other will control movement using the arrow keys. The problem I am having is that using keyPressed negates WASD when arrows are pressed and vice versa. I have been messing around with it for a really long time. Does anyone know a work around or notice something that I am doing wrong?
//global variables
int wide = 600; //canvas width
int tall = 600; //canvas height
int s = 50; //player size
float speed = 2.5; //player movement speed
//colors
int redColor = #CB4646; //player 1 color
int blueColor = #4652CB; //player 2 color
int backgroundColor = #DBE3B3; //background color
float player1X = 600/3-s; //HOW COME width/3 DOESN'T WORK??????????
float player2X = 600*2/3;
float playerY = 600/2-(s/2);
//players
Player player1 = new Player(player1X, playerY, s, speed, "wasd", redColor); //player 1
Player player2 = new Player(player2X, playerY, s, speed, "arrows", blueColor); //player 2
//setup
void setup(){
background(backgroundColor);
size(wide, tall);
smooth();
println(player2.controls);
}
//draw
void draw(){
background(backgroundColor);
player1.usePlayer();
player2.usePlayer();
}
class Player{
//class variables
float x; // x position
float y; // y position
int s; //size
float speed; //speed
String controls; //controls
int colors; //player color
char keyControls [] = new char [4];
//construct
Player(float tempX, float tempY, int tempS , float tempSpeed, String tempControls, int tempColors){
x = tempX;
y = tempY;
s = tempS;
speed = tempSpeed;
controls = tempControls;
colors = tempColors;
}
void usePlayer(){
// draw player
fill(colors);
rect(x, y, s, s);
//move player
keyPressed();
//wraparound
boundaries();
}
void keyPressed(){
//sets controls for wasd
if(controls == "wasd"){
if(key == 'w' || key == 'W'){
y -= speed; //move forwards
}
if(key == 's' || key == 'S'){
y += speed; //move backwards
}
if(key == 'd' || key == 'D'){
x += speed; //move right
}
if(key == 'a' || key == 'A'){
x -= speed; //move left
}
}
//sets controls for arrows
if(controls == "arrows"){
if(key == CODED){
if(keyCode == UP){
y -= speed; //move forwards
}
if(keyCode == DOWN){
y += speed; //move backwards
}
if(keyCode == RIGHT){
x += speed; //move right
}
if(keyCode == LEFT){
x -= speed; //move left
}
}
}
}
//pacman style wraparound
void boundaries(){
if(x == width) x = 2;
if(y == height) y = 2;
if(x == 0) x = width-s;
if(y == 0) y = height-s;
}
}
Track your keys independently, don't rely on the event globals.
boolean[] keys = new int[255];
void keyPressed() {
keys[keyCode] = true;
}
void keyReleased() {
keys[keyCode] = false;
}
void draw() {
updatePlayers();
drawStuff();
}
void updatePlayers() {
if(keys[LEFT]) { p1.move(-1,0); }
if(keys[RIGHT]) { p1.move(1,0); }
if(keys[UP]) { p1.move(0,-1); }
if(keys[DOWN]) { p1.move(0,1); }
if(keys['a']) { p2.move(-1,0); }
if(keys['d']) { p2.move(1,0); }
if(keys['w']) { p2.move(0,-1); }
if(keys['s']) { p2.move(0,1); }
}
Note this has to be a series of if statements, because you want to handle all pressed keys. If someone's holding left and right, p1 will move left, and right.
Also note that this example code doesn't filter for the higher-than-255 codes you get for special keys, so you probably want to put an "if(keyCode>255) return" at the start of the event handlers.
Is key a global variable? I don't see it getting passed to the Player. If it's global, then it can only hold one key at a time, which precludes controlling two players at once.
Here is my Arduino/Processing code that I used to handle simultaneous key presses (to move diagonally). It fixes the issue with boolean[] cannot be cast to int[] error as shown by #Brannon and uses keyCodes instead of key.
import processing.serial.*;
boolean[] keys = new boolean[255];
Serial port;
void setup() {
port = new Serial(this, Serial.list()[1], 9600);
}
void draw() {
// loop through boolean array and see which ones (index = keyCode)
// are true, then write to them.
for(int i = 0; i < 255; i++) {
if(keys[i]) {
if (i == 87) { port.write('w'); }
if (i == 65) { port.write('a'); }
if (i == 83) { port.write('s'); }
if (i == 68) { port.write('d'); }
}
}
}
void keyPressed() {
keys[keyCode] = true;
}
void keyReleased() {
keys[keyCode] = false;
}
Hey guys i'm making a maze game and I'm trying to figure out how to make a 2D collision smooth. Currently I have some really bad collision code that I thought up since I haven't done this part yet and it is glitchy and sometimes goes inside the wall then you can't get out.
My code:
public void checkCollision() {
Rectangle player_rectangle = new Rectangle(player.getX(),player.getY(),32,32);
for(Wall wall : walls) {
Rectangle wall_rectangle = new Rectangle(wall.getX(), wall.getY(), 32,32);
if(player_rectangle.intersects(wall_rectangle)) {
if(player.xspeed == 1) {
player.xspeed = 0;
player.x -= 1.2;
} else {
if(player.xspeed == -1) {
player.xspeed = 0;
player.x += 1.2;
}
else
if(player.yspeed == 1) {
player.yspeed = 0;
player.y -= 1;
} else {
if(player.yspeed == -1) {
player.yspeed = 0;
player.y += 1;
}
}
}
}
}
}
What is a better way to do the collision? here is a picture of the types of maps I will have:
EDIT:
New Collision code:
if (player_rectangle.intersects(wall_rectangle)) {
Rectangle intersection = (Rectangle) player_rectangle.createIntersection(wall_rectangle);
if (player.xspeed > 0) {
player.x -= intersection.getWidth();
}
if (player.yspeed > 0) {
player.y -= intersection.getHeight();
}
if (player.xspeed < 0) {
player.x += intersection.getWidth();
}
if (player.yspeed < 0) {
player.y += intersection.getHeight();
}
Print(Integer.toString(intersection.width) + ", " + Integer.toString(intersection.height));
}
Movement Code:
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if(key == KeyEvent.VK_LEFT) {
xspeed = -1;
} else {
if(key == KeyEvent.VK_RIGHT) {
xspeed = 1;
} else {
if(key == KeyEvent.VK_UP) {
yspeed = -1;
} else {
if(key == KeyEvent.VK_DOWN) {
yspeed = 1;
}
}
}
}
}
Thanks for any help you can give me.
You can use Rectangle.createIntersection(Rectangle).
If the player moves to a positive direction, just subtract the width and height of the resulting Rectangle from his position, if he moves to a negative, add them.
Don't set the speed to zero, this could cause the player to hang.
EDIT
if (playerRectangle.intersects(wallRectangle) {
Rectangle intersection = (Rectangle) playerRectangle.createIntersection(wallRectangle);
if (player.xspeed > 0) {
player.x -= intersection.getWidth();
}
if (player.yspeed > 0) {
player.y -= intersection.getHeight();
}
if (player.xspeed < 0) {
player.x += intersection.getWidth();
}
if (player.yspeed < 0) {
player.y += intersection.getHeight();
}
}
EDIT2
As far as I know, keyPressed is only triggered when you press a key, and not when you release it. Try it like this:
private boolean up, down, left, right;
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KEyEvent.VK_UP) {
up = true;
}
...
}
public void keyReleased(KeyEvent e) {
if (e.getKeyCode() == KEyEvent.VK_UP) {
up = false;
}
...
}
// Call this in the mainthread
public void updateMovement() {
if (up) {
player.xspeed = 1;
}
...
}
So in every frame, you update the movement, move the player and then check the collision.
Myself shweta dodiya.I am having an problem related to sensor and logic in j2me which i had implemented for achieving the result in my project.The logic which i had implemented is as follows:-
sensor= (SensorConnection) Connector.open("sensor:acceleration");
try {
data = sensor.getData(1);
} catch (IOException ex) {
ex.printStackTrace();
}
for (int i = 0; i < data.length - 1; i++) {
value[i] = data[i].getDoubleValues()[0];
}
CurrentValX = value[0];//X-axis of sensor
CurrentValY = value[1];//y-axis of sensor
if (CurrentValX < PreValueX1) {
left = false;
right = true;
} else if (CurrentValX > PreValueX1) {
left = true;
right = false;
}
if (CurrentValY < PreValueY1) {
down = false;
up = true;
} else if (CurrentValY > PreValueY1) {
down = true;
up = false;
}
if (right == true && ballX < Scrwidth - 15) {
ballX += 4;
} else if (left == true && ballX > 15) {
ballX -= 4;
}
if (down == true && ballY < Scrheight - 15) {
ballY += 4;
} else if (up == true && ballY > 15) {
ballY -= 4;
}
CurrentValY = PreValueY1;
CurrentValX = PreValueX1;
//check for the collision of ball with the other object like brick
if (bricksprite.collidesWith(ballSprite, true)) {
if (right) {
ballX -= 10;
}
if (left) {
ballX += 10;
}
if (up) {
ballY += 10;
}
if (down) {
ballX -= 10;
}
}
The problem i am having is in the collision of the ball and the bricks.when it get collide i want to move ball in the opposite direction of the collision.But sometime the ball instead of moving in opposite direction it keep moving in same direction.I had getting the direction of the ball through the boolean up,down,left,right.
Please help me to solve it and guide me and correct me if i m wrong somewhere
Thanks in advance
I haven't read your code , But in past I have coded the same kinda game,
In that I have applied following logic;
1.when ball colides suppose consider ball is moving from right to left than collides at left wall at some angel. here your x and y was decreasing in uniform manner upon colission your x should increase while y should be decreasing with the same fashion.
2.when ball colides vertical wall , y should invert x should be same..
I hope it clears up the logic.