Moving image leaving trail and directional movement according to mouse position -Processing - processing

So I managed to make most of the exercise but can't think of a way to make the trail of the moving image. Also, in the video ball moves in the direction of mouse position.
However, when I tried to do that, mouse position is changing every time and the ball is following the mouse while moving. The velocity had to be calculated using the mouse position. Any help would be appreciated.
This is how it should look: https://streamable.com/9jdc3
My code:
PImage ball, bFire;
int xPosB, yPosB, bW, bH, bFW, bFH, velocityX, velocityY;
boolean bMoving;
void setup() {
size(1024, 512);
//loading images
ball = loadImage("ball.png");
bFire = loadImage("ballFire.png");
//resizing images
ball.resize(ball.width/4, ball.height/4);
bFire.resize(bFire.width/4, bFire.height/4);
//starting values
//ball
xPosB = width/2;
yPosB = height/2;
}
void draw() {
background(0);
//draw ball
imageMode(CENTER);
image(ball, xPosB, yPosB);
//draw fire ball
if (bMoving) {
image(bFire, xPosB, yPosB);
xPosB+=velocityX;
yPosB+=velocityY;
}
//colision detection
if (xPosB-bFire.width/2 <= 0 || xPosB+bFire.width/2 >= width) {
velocityX*=-1;
} else if (yPosB-bFire.height/2 <= 0 || yPosB+bFire.height/2 >= height) {
velocityY*=-1;
}
}
void mousePressed() {
if (mouseButton == LEFT) {
bMoving=!bMoving;
velocityX = mouseX/100;
velocityY = mouseY/100;
}
}

I can't repoduce the problem you describe - of the ball following the mouse.
I can tell you that the mousepressed() you use is incorrect.
You assign the velocity, but because mouseX and mouseY will always be positive the ball will always move to the right and down.
Try the code below, it sets the velocity to the difference between the mouse and the current position of the ball. The ball will now always move towards the mouse.
void mousePressed() {
if (mouseButton == LEFT) {
bMoving=!bMoving;
velocityX = (mouseX - xPosB) / 50;
velocityY = (mouseY - yPosB) / 50;
}
Second point: I don't know how your ballFire.png looks, but right now it is drawn at the exact same X/Y location of the ball. This cannot give you a trailing effect, for that you'll have to draw the fireball a little behind the ball.
Try the code below:
//draw fire ball
if (bMoving) {
image(bFire, xPosB-velocityX, yPosB-velocityY);
xPosB+=velocityX;
yPosB+=velocityY;
}
//draw ball
imageMode(CENTER);
image(ball, xPosB, yPosB);
It draws the fireBall behind the ball based on the velocity. So faster means more distance. You can tweak this distance of course. If you want multiple firballs as trailing effect, draw the fireball multiple times with different offsets.
Final note: you'll want to draw the ball last, else the fireball will be drawn half over the normal ball.

Related

Jumping realistic in Processing with PVectors

I tried to make a jump look realistic, while I watched through the Videos:
The Natur of Code - The Coding Train
I got into PVectors. I strongly recomend watching him. But to get to my question, everything seems to work, exept that it draws the rectangle (my PVector) the way I want.
void keyPressed() {
if (keyCode == UP) {
for (int i = 0; i < 16; i++) {
location.sub(velocity);
velocity.sub(acceleration);
h.display();
background(0);
}
velocity.set(0, 15);
}
}
That's the Code, I expect it to "jump", but nothing realy happens. You can see that the rectangle get's drawn again (on the same spot), but there's no movement. It's definitly an issue with the drawing of the background or something, I don't know what exaclty though.
The nature of your question is unclear. You mentioned issues regarding the background interfering with your rectangle after the UP arrow key is pressed. This is likely because background(0) is called immediately after h.display(). I would remove background(0) from your loop if it's a display issue.
Other than that, there seem to be other issues with the loop itself. When the UP key is pressed, h is affected by acceleration only for 16 frames. To make your object more realistic, gravity (or whatever acceleration you choose) should constantly be acting upon the object.
With that in mind, here's a solution for you.
void keyPressed() {
if (keyCode == UP) {
// Make the character 'jump' upwards when the UP arrow is pressed.
// Setting the velocity should be the only thing happening when the key is pressed.
velocity.set(0, -2);
}
}
void draw() {
// Reset the background each frame so rectangles don't overlap.
background(255);
// Always draw the rectangle AFTER resetting the canvas.
h.display();
// Change the object's location by it's velocity.
location.add(velocity);
// And chance the object's velocity by it's acceleration.
// Since acceleration is the acting force of gravity in this situation, acceleration need not be changed.
velocity.add(acceleration);
// Prevent the rectangle from falling through the bottom of the canvas.
if(location.y > height - 5) location.y = height - 5;
}
// You negleteced to define your variables in your code snippet. Here they are.
PVector location = new PVector(0, 0);
PVector velocity = new PVector(0, 0);
PVector acceleration = new PVector(0, 0.1); // Notice that acceleration's y-value is 0.01. This is so you can see the effect of gravity.
// Define your rectangle object.
Object h = new Object();
class Object {
Object() {} // Constructor.
void display() {
// Draw the rectangle at the x- and y-positions of the location vector.
// The '+ width/2' places it at the center of the screen.
rectMode(CENTER);
rect(location.x + width/2, location.y, 10, 10);
}
}

How to rotate the ball in the direction its moving?I try to use the rotate function but that throws everything off?

//declaringglobalvaribales
float dia1=50;
//diameteroftheface
float x=400;
float y=400;
float speedX=4;
float speedY=0;
//setup
void setup() {
size(810, 810);
} //draw
void draw() {
background(225);
fill(225, 0, 0);
stroke(0);
ellipse(x, y, dia1, dia1);
fill(0, 225, 0);
//a nose
triangle(x, y, x+10, y+10, x-10, y+10);
//movingtheballXway
x=x+speedX;
//movingtheballYway
y=y+speedY;
//if it hits the left or right corners it will turn around
if (x>width-dia1/2 || x<2+dia1/2) {
speedX=speedX*-1;
}
// it its hits the top or bottom it will turn around
if (y>height-dia1/2 || y<2+dia1/2) {
speedY=speedY*-1;
}
// this code to move it according to the keys W S D A
void keyPressed() {
if (keyCode=='W') {
speedX=0;
speedY=-4;
}
if (keyCode=='S') {
speedX=0;
speedY=4;
}
if (keyCode=='A') {
speedX=-4;
speedY=0;
}
if (keyCode=='D') {
speedX=4;
speedY=0;
}
}
I made this ball with a nose, which moves around the screen with the keys W S D A. If it hits the edges it will bounce back.
I'm trying to change the direction the ball is facing to make it face the same way as it's moving. I wanted to use rotate for this, but once I use rotate it throws all the coordinates off. Rotating it back doesn't help either.
I have commented out the stuff I have tried to do. For example, I tried to translate it to 250,250 and then rotate it afterwards, but then the X and Y coordinates are switched. Also, the ball won't go all the way to the corners and it moves out (since it's translated down).
What kind of rotation/translation logic do I need to change?
It is likely that using the rotate function on your triangle is wreaking havoc as you are performing the rotate on several variables in your draw loop because you're not telling processing exactly which object you want to transform. One way to do this is to look up the pushMatrix and popMatrix functions (google "processing pushMatrix" to see helpful info for how to use the type and associated functions). It would be cumbersome to implement this into your code as the triangle is created in your draw loop every frame. An easy way to make transformations to a specific shape you have (in your instance, a triangle) is to store it as a PShape and then make transformations as you need to. Since PShape's can easily be transformed using PShape functions you don't need to worry about your transformations effecting other variables (so no need to use push/popmatrix. Here is a commented version of your code that implements your Triangle as a PShape.
//declaringglobalvaribales
float dia1=50;
//diameteroftheface
float x=400;
float y=400;
float speedX=4;
float speedY=0;
//Initialize PShape which we can later store a triangle in
PShape tri;
void setup() {
size(810, 810);
//Initialize triangle - this triangle faces right
tri = createShape(TRIANGLE, 0, 10, 0, -10, 10, 0);
}
void draw() {
background(225);
fill(225, 0, 0);
stroke(0);
ellipse(x, y, dia1, dia1);
fill(0, 225, 0);
//Draw the stored PShape at x and y coordinate
shape(tri,x,y);
//movingtheballXway
x=x+speedX;
//movingtheballYway
y=y+speedY;
//if it hits the left or right corners it will turn around
if (x>width-dia1/2 || x<2+dia1/2) {
speedX=speedX*-1;
//Flip PShape rotation
tri.rotate(PI);
} // it its hits the top or bottom it will turn around
if (y>height-dia1/2 || y<2+dia1/2) {
speedY=speedY*-1;
//Flip PShape rotation
tri.rotate(PI);
}
}
// this code to move it according to the keys W S D A
void keyPressed() {
if (keyCode=='W') {
speedX=0;
speedY=-4;
//reset triangle orientation (transformation matrix) to original then rotate to face UP
tri.resetMatrix();
tri.rotate(-PI/2);
}
if (keyCode=='S') {
//reset triangle orientation (transformation matrix) to original then rotate to face DOWN
speedX=0;
speedY=4;
tri.resetMatrix();
tri.rotate(PI/2);
}
if (keyCode=='A') {
//reset triangle orientation (transformation matrix) to original then rotate to face LEFT
tri.resetMatrix();
tri.rotate(PI);
speedX=-4;
speedY=0;
}
if (keyCode=='D') {
//reset triangle orientation (transformation matrix) to original - it is already pointing right
tri.resetMatrix();
speedX=4;
speedY=0;
}
}
I suspect your next step, or a more efficient way to write this piece of code might be to begin to implement PVectors (google processing PVectors to see helpful info for how to use the type and associated functions) for position and direction of your 'ball'. Here is some commented code that begins to show you how you might implement this in your current code. Although there are many improvements that can be made on this. For more information on how vectors work in processing follow this tutorial - http://natureofcode.com/book/chapter-1-vectors/
//declaringglobalvaribales
//diameteroftheface
float dia1=50;
//initialize position PVector and tell it where you want it to be - in this case 400,400
PVector position = new PVector(400, 400);
//how many steps you want your position to move per frame
float speed=4;
//initialize direction vector as 0,0 - the ellipse will not move until you give it a
//direction as it is initialized with no direction
PVector direction = new PVector(0, 0);
void setup() {
size(810, 810);
}
void draw() {
background(225);
fill(225, 0, 0);
stroke(0);
//draw ellipse at your position PVector using the PVectors x and y values
ellipse(position.x, position.y, dia1, dia1);
fill(0, 225, 0);
//drawing a line to indicate what direction the ellipse is heading in using the position coordinates and the position plus direction
line(position.x, position.y, position.x+direction.x*4, position.y+direction.y*4);
// add the direction to the position to make it move
position =position.add(direction);
//if the position PVector is close to sketch edges invert its direction by multiplying direction PVector by -1
if (position.x>width-dia1/2 || position.x<2+dia1/2) {
direction.mult(-1);
}
if (position.y>height-dia1/2 || position.y<2+dia1/2) {
direction.mult(-1);
}
}
// this code to move it according to the keys W S D A
void keyPressed() {
//set the direction coordinates based on keypresses
//also multiply the direction by speed variable so it moves at a speed set at top of script
if (keyCode=='W') {
direction.y = -1*speed;
direction.x = 0;
}
if (keyCode=='S') {
direction.y = 1*speed;
direction.x = 0;
}
if (keyCode=='A') {
direction.x = -1*speed;
direction.y = 0;
}
if (keyCode=='D') {
direction.x = 1*speed;
direction.y = 0;
}
}
If you have a center point, an angle you want to face, and a distance from that center, you can use cos() and sin() to calculate the end point. Here's a simple example:
float angle = 0;
float distance = 25;
void draw(){
angle += .01;
float startX = width/2;
float startY = height/2;
float endX = startX + cos(angle)*distance;
float endY = startY + sin(angle)*distance;
background(255);
line(startX, startY, endX, endY);
}
In the future, please try to narrow your question down to an MCVE like this before posting.

Making an object bounce of an other object that is moved by mouseY/mouseX in processing

I am pretty new with processing and need some help. I'm trying to build a simple kickball game. Easy idea: when the ball hits the yellow bar, the ball bounces of. To keep the ball "alive" you have to make it bounce of the yellow bar. I've successfully found code for the bouncing ball (it now bounces of the bottom of the window), and I've also successfully created a bar that moves with the mouse. What I haven't been able to create so far is for the ball to actually bounce of the bar. Looking for som help here!! Thanks!!
float ballX = 100;
float ballY = 0;
float h = 50;
int x, y;
//create a variable for speed
float speedY = 2;
void setup() {
size(400,400);
smooth();
noStroke();
// change the mode we draw circles so they are
// aligned in the top left
ellipseMode(CORNER);
}
void draw() {
//clear the background and set the fill colour
background(0);
fill(255);
//draw the circle in it's current position
ellipse(ballX, ballY, h,h);
//add a little gravity to the speed
speedY = speedY + 0.5;
//add speed to the ball's
ballY = ballY + speedY;
//bar
x = mouseX;
y = mouseY;
fill(255, 255, 0);
rect(x, y, 50, 10);
if (ballY > height - h) {
// set the position to be on the floor
ballY = height - h;
// and make the y speed 90% of what it was,
// but in the opposite direction
speedY = speedY * -0.9;
//switch the direction
//speedY = speedY;
}
else if (ballY <= 0) {
// if the ball hits the top,
// make it bounce off
speedY = -speedY;
}
}
I'd warn you against just copy-pasting code you found on the internet. You have to really understand what it's doing, otherwise you're going to have a ton of headaches as your code becomes more complicated. Try to rewrite the logic yourself, that way you understand exactly how the bouncing works.
To figure out whether the ball is intersecting the paddle, I'd recommend taking out a piece of paper and a pencil and drawing some examples. Try to figure out a pattern of what the position and size of the ball and paddle are when they're intersecting.
But basically, you need to check whether the ball is "inside" the bounds of the rectangle. This is true if the ball is to the right of the left side of the paddle, to the left of the right side of the paddle, below the top of the paddle, and above the bottom of the paddle.

Processing bat and ball game on vertical axis

This is the code I have at the moment but I want to put the bat on the y axis and have it move up and down vertically rather than horizontally, and have the ball bounce in a left to right motion rather than up and down. Help is needed quickly. Thanks.
int x=250; // Horizontal position of ball
int direction_x=2; // Change in horizontal position each time draw() executed
int y=150; // Vertical position of ball
int direction_y=2; // Change in horizontal position each time draw() executed
int lives=3;
int score=0;
void setup()
{
size(400,400); // Create a window 400x400 pixels
}
void draw()
{
background(255,255,255); // Clear screen to white
fill(0,255,0); // Set fill colour to blue
rect(mouseY-60,380,120,20); // Position rectangle using mouse
fill(0,0,255);
ellipse(x,y,20,20); // Draw blue disk centered on x,y diameter 20
x=x+direction_x; // Update position
if(x<10) direction_x=-direction_x; // Reverse direction if hit boundary
if(x>(width-10)) direction_x=-direction_x;
y=y+direction_y;
if(y<10) direction_y=-direction_y;
// if(y>(height-10)) direction_y=-direction_y;
if(y>(height-10)) // If ball bits bottom of screen then miss..
{
direction_y=-direction_y; // Bounce
lives--; // Reduce lives by one
if(lives==0) exit(); // If lives is zero then quit
}
if((y>(height-30))&&(abs(mouseX-x)<60)) // If ball has bit paddle then..
{
direction_y=-direction_y; // Bounce
score++; // Increase score by one
}
textSize(32);
fill(0,0,255);
text(score, 10, 30); // Display score
text(lives,width-30, 30); // Display lives
}
Since help is needed quickly, you'll have better luck if you ask a specific "I tried X, expected Y, but got Z instead" type question. It's hard to help with general "how do I do this" type questions, other than to offer general tips.
That being said, there are two main approaches that I can think of:
Option One: Break your problem down into smaller steps. Start with a blank sketch and get just the paddle working how you want it to. Then try adding the ball. After that's working, then try adding game logic. This is the better option here.
Option Two: Since you seem to almost have this working going up and down, you could just rotate everything 90 degrees by using the rotate() function. This is a bit of a hack though.
Thanks Kevin, got it working at last, turns out I just had to change co-ordinates of the paddle from (mouseX,0,0,0) to (0, mouseY,0,0) and needed to add in an additional line of code to change the axis parameters. I was doing my age old trick of over complicating things.
int x=250; // Horizontal position of ball
int direction_x=2; // Change in horizontal position each time draw() executed
int y=150; // Vertical position of ball
int direction_y=2; // Change in horizontal position each time dra) executed
int lives=3;
int score=0;
void setup()
{
size(400,400); // Create a window 400x400 pixels
}
void draw()
{
background(255,255,255); // Clear screen to white
fill(0,255,0); // Set fill colour to blue
rect(0,mouseY-60,20,120); // Position rectangle using mouse
fill(0,0,255);
ellipse(x,y,20,20); // Draw blue disk centered on x,y diameter 20
x=x+direction_x; // Update position
if(x<10) direction_x=-direction_x; // Reverse direction if hit boundary
if(x>(width-10)) direction_x=-direction_x;
y=y+direction_y;
if(y<10) direction_y=-direction_y;
// if(y>(height-10)) direction_y=-direction_y;
if(y>(height-10)) // If ball bits bottom of screen then miss..
{
direction_y=-direction_y; // Bounce
lives--; // Reduce lives by one
if(lives==0) exit(); // If lives is zero then quit
}
if(x<10)
{
direction_x=-direction_x; // Bounce
x=30; // Force x to beyond the paddle on a restart
lives--; // Reduce lives by one
if(lives==0) exit(); // If lives is zero then quit
}
if((x<30)&&(abs(mouseY-y)<60)) // If ball has bit paddle then..
{
direction_x=-direction_x; // Bounce
score++; // Increase score by one
}
textSize(32);
fill(0,0,255);
text(score, 10, 30); // Display score
text(lives,width-30, 30); // Display lives
}

Breakout (the game) in Processing

So, I am creating the game breakout in processing (programming language) but can't quite figure out a function to check for collision against the bat.
So far the section I have written for collision against the bat only collides the ball against the base and returns it in the opposite direction. For now, the game is a never ending phenomenon where the ball just collides with the walls. What I am trying to do is, collide the ball against the bat.
Oh this is my homework, so just please point me in the right direction instead of doing it for me.
Here's the code:
// Basic Breakout game
// Code from Matthre Yee-King
// brick position
float brickX;
float brickY;
// brick width and height
float brickH;
float brickW;
// ball position
float ballX;
float ballY;
// ball diameter
float ballD;
// ball direction
float ballDx;
float ballDy;
// bat position
float batX;
//bat width
float batW;
float batH;
//bat colour
float batB;
void setup() {
size (500, 500, P2D);
// set sizes of game items
brickW = 100;
brickH = 50;
batW = 100;
batH = 25;
ballD = 25;
batB = 255;
// random brick position
brickX = random(0, width - brickW);
brickY = random (0, height / 2);
// bat in the centre
batX = (width/2) - (batW/2);
// ball atop bat
ballX = batX + (batW/2);
ballY = height - batH - (ballD/2);
// ball movement
ballDx = random(-5, 5);
ballDy = -5;
rectMode(CORNER);
ellipseMode(CENTER);
}
void draw() {
// check for ball collision
// with top or sides of bat
checkBallAgainstBat();
// check for ball collision with
// left right and top walls
// and bounce
checkBallAgainstWalls();
// check ball against brick
checkBallAgainstBrick();
// move the ball
ballX += ballDx;
ballY += ballDy;
background(0);
// draw the bat
fill(0, 255, 0);
rect(batX, height - batH, batW, batH);
// draw the brick
fill(0, 0, batB);
batB = (batB + 10) % 255;
rect(brickX, brickY, brickW, brickH);
// draw the ball
fill(255, 0, 0);
ellipse(ballX, ballY, ballD, ballD);
if (keyCode == 37) { // left cursor key
batX -= 10;
// keep it on the screen
if (batX < 0) {
batX = 0;
}
}
if (keyCode == 39) {
batX += 10;
if (batX > (width - batW)) {
batX = width - batW;
}
}
}
// when they let go of the key, reset the keyCode
void keyReleased() {
keyCode = -1;
}
// this function checks if the ball has hit the top or sides of the bat and
// updates its direction as appropriate so the ball bouncs off the bat
void checkBallAgainstBat() {
if (ballY + ballD > height - batH) {
ballDy *= -1;
}
}
// this function checks if the ball has hit the brick. It should bounce off
// the brick and return true if so
boolean checkBallAgainstBrick() {
return false;
}
// this function checks if the ball has hit the top, left or right
// walls and update its
// direction as appropriate so the ball bounces off the walls
void checkBallAgainstWalls() {
if (ballX + ballD > width) {
ballDx *= -1;
}
if (ballX - ballD < 0) {
ballDx *= -1;
}
if (ballY - ballD < 0) {
ballDy *= -1;
}
}
Since the bat in breakout is a fixed width, your collision detection can be quite simple (in pseudo-code):
if (lower_edge(ball) > top_edge(bat)) {
// the ball has entered territory where it might have collided
if ((left_edge(ball) <= right_edge(bat)) && (right_edge(ball) >= left_edge(bat))) {
// the ball's within the horizontal bounds of the bat, so it's a "hit"
... calculate deflection ...
} else {
// oops, ball's gone past the bat and wasn't hit
strike_out();
} else {
// ball's still above the bat somewhere. do nothing
}
In english: If the ball's lower edge has gone past where the top edge of the bat is, we've POSSIBLY got a collision. This is only checking the vertical axis of the play field. You then check if the left or right edges of the ball fall within the horizontal location of the bat. If neither side of the ball overlaps the bat, then you've lost. Otherwise you've collided and you do the collision detection.

Resources