How to calculate needed velocity for a ball to hit targer? - java

I want to calculate velocity for ball to hit target(my ball/finger).
x and y of my ball are know and are changing while I'm moving my finger but assume that it is not changing (X and Y are some random number) and ball that should reach my finger is coming from left upper corner (x=0,y=0).
How to calculate velocityX and velocityY for that ball in order to hit me ?

You could set velocityX to negative if the ball is X is greater then the target's X else set velocity to a positive number if it is less then the target's X. This would make the ball move towards the X coordinate of the target. Just do the same for the y Axis and the ball should move towards the target. However, this may cause the ball to "shake" when it reaches the target so, in order to fix this, set velocityX and velocity to 0 when it reaches the target.
Hope this helped.

Related

Collision detection between brick and ball (breakout, brick breaker)?

I'm working on a brick breaker game in JavaFX (FXGL). The collision detecting is working like this:
Bricks and players have a x, y position in the game world (placed in LEFT, TOP).
When a collision is detected (this is done by the engine) I use the x, y position to detect where the ball is colliding with the brick to calculate the next direction. The ball direction is created by a velocity vector with (x, y) speed. The collisionLogicSecurityPadding is a small padding which is added since the collision is only detected inside the box. (It's not possible to get the ball and brick exactly at the same x, y coordinates)
if (ball.getX() > levelBrick.getX() - ball.getWidth() + collisionLogicSecurityPadding &&
ball.getX() < levelBrick.getX() + levelBrick.getWidth() - collisionLogicSecurityPadding) {
//velocity.getX(), -velocity.getY()
} else {
//-velocity.getX(), velocity.getY()
}
So I measure if the ball is inside the brick with it x position. If this is the case the collision is TOP or BOTTOM. If not RIGHT or LEFT.
However this is causing the issue when the ball is hitting near the edge it detects wrong. Here a short clip: https://i.imgur.com/U8ybhRl.mp4
The issue is that the x is smaller than the area where it thinks it's TOP or BOTTOM so it's switching the X direction which is causing an issue.
My question here is how to avoid this? Is there any way I can solve the collision that it's working correctly? When I'm looking online the most tutorials are only checking top or bottom collision.
I think you could change the detection of TOP, BOTTOM, LEFT, RIGHT collisions to where the collision happened relative to the ball. Assuming the preservation of momentum you just need to negate the X- or Y-velocity.
In the example above the ball clearly generates a collision TOP and LEFT to his center of mass. Therefore it is impossible to generate a RIGHT collision which would generate the behavior you described. This leaves the Problem, that you do not know yet whether it was a collision on the LEFT or TOP. But since the Vector was pointing to the RIGHT (positive X-Movement), it is impossible to generate a collision on the LEFT. The collision must have happened at the TOP and therefore the Y-velocity needs to be multiplied by -1.
As long as the ball is the only moving object this method cannot generate weird behavior. As soon as you have an Object moving faster then the ball, you need additional checks: An Object hitting the ball on its left, while it is already in a general movement towards right will increase the X-velocity.
As I understood your question it seems to me like your issue is that the red box goes in an incorrect direction after bouncing on an edge.
I think you need to detect collision in three instances.
Top/Bottom
Left/Right
An Edge
If the collision occurs at an edge you need to send it in the same x direction as before with reducing the speed it goes in the direction y. y speed should always be less than initial speed and in the same direction as before.
I think above would solve your issue.

Rectangle and Circle Collision Java using .intersection

I am making a breakout game for a school project. The only problem I am running into is the Ball Bouncing when the Ball and Bricks collide. I used ball1.getEllipse().intersects(b.getRectangle()) allowing me to figure out when it is colliding and delete the brick. The bouncing chances depending on the side it collided with. This is the main problem. The .intersect piece does not show me which side the brick gets hit by. I need this to know whether to change the x or y speed. If anyone has any idea on how to figure this out, please leave your input (I have been trying to think of a solution for 5 hours, I gave up)
public void collision(int i) {
for (Block b : blocks) {
if (ball1.getEllipse().intersects(b.getRectangle())) {
if (!b.isDestroyed()) {
b.destroy();
blockCount-=1;
ball1.brickBounce();`public void collision(int i) {
From what I understand from your question, you want to know which side of the rectangle the ball is hitting. A simple way of doing this would be to take the position of the ball and the position of the rectangle and compare the two. If the ball's x position is less than the rectangles x position - half its width(to get the x position of the bound), then the ball hit on the left side. You can then do the opposite for the right side. Checking if it hit on top or bottom is similar just with the y positions and the rectangle's height. Do note that I'm assuming the x and y position of each shape is the center, if not only minor adjustments should have to be made to get the same result as if it were the center.

Java - Breakout physics, ball direction on paddle collision?

I'm creating a Breakout game to familiarize myself with Java.
Currently I've got everything working but I've noticed that the ball seems to take off in the same direction.
I've programmed it so when the ball hits the paddle the Y velocity is reversed. This works, but the ball seems to follow the same route...
How would a make the collision seem more realistic?
When the ball hits the left side of the paddle, I want to redirect it back to the left but I'm not sure at which angle to reflect it. Can anyone provide a formula to help me work out the angle at which I need to direct the ball upon contact with either the left or right side of the paddle?
If the ball hits the paddle from the top, negate Y velocity.
If the ball hits the paddle from the side, negate X velocity.
Reversing the vertical velocity is the correct thing to do for a perfectly elastic collision, which is what you want in a breakout game (the ball keeps it's total velocity after the collision).
The problem of following the same route can be avoided either by randomizing the initial ball position and velocity, or by changing the collision dynamics to be unrealistic. You could either add a small random component to both coordinates (taking care to keep the total velocity the same), or send the ball at a different angle, depending on where it hits the pad (which is what many games of this type do).
To do the later, you need to calculate the absolute position where the ball hits the pad, normalize it (by subtracting the pad position and dividing by the pad length), and map it into a angle range (maybe -80 to 80 degrees). You can then calculate the desired horizontal and vertical velocities using trigonometric functions.
One idea might be to use motion of the paddle to vary the direction a bit. Say, if the paddle is moving to the right when hitting the ball, change the X velocity of the ball to the right a little in addition to reversing the Y direction. That provides a way for the user to actually use some skill to put the right "English" on the ball.
There are two separate problems involved, a design problem and the physics problem. In the end, the physics problem might have the easier solution:
Compute the collision point on the paddle
Compute the instantaneous horizontal velocity pvx of the paddle
Compute the normed outward surface normal (nx,ny) at the impact point. This is the design decision, in the middle part of the paddle one probably wants (nx,ny)=(0,1), while on the left side (nx,ny)=(-1,0) or generally in WNW direction, on the right side correspondingly (nx,ny)=(1,0) or in the general ENE position.
Use the physics formula for a collision with a moving infinitely massive object to compute the new velocity vector (vx,vy):
dot = nx*(vx-pvx)+ny*vy
vx = vx - 2*dot*nx
vy = vy - 2*dot*ny
One may check if the dot product dot is positive to avoid spurious collision computations if paddle and ball do not separate fast enough after collision.

Direction of a moving sprite

I'm doing a simple breakout game and I have some problem to understand how I should handle speed and direction of the ball to move it in different diagonal paths. I'm using this code in an update method:
xPos += xSpeed * direction;
yPos += ySpeed * direction;
If I use different vaules of xSpeed = 2 and YSpeed = 1 I can change to different diagonal paths, but I still want the same speed. If I increase value of xSpeed = 4 to get another diagonal path, then the speed is also increased, and I want the ball to move in the same speed. For the value of direction I use 1 or -1. But I guess it would be better to change the value of direction to get diagonal paths in degrees? In a breakout game the ball has to bounce back in the oppesite direction. I'm not good in math, so I would preciate some help to solve this. Any ideas how I can improve my code?
You could use sine and cosine functions to get the relative movement in x and y axis.
Like:
xPos += speed * Math.sin(movementAngle);
yPos += speed * Math.cos(movementAngle);
Using the above (polar coordinates) in various animations has the advantage of ease in modyfing direction or velocity of movement (which are speed and movementAngle variables respectively). When using cartesian coordinates (x and y position), change in either velocity or direction of movement would require non-obvious changes to both x and y.
Formulas in the solution above are nothing more than conversion from polar to cartesian coordinates.
Edit: to get the more "natural" behaviour, when movementAngle of 0 means moving right, PI/2 - up, PI - left and 3*PI/2 - right, use the following:
xPos += speed * Math.cos(-1*movementAngle);
yPos += speed * Math.sin(-1*movementAngle);

Moving Objects Help

I want to know how is it possible,I could have an Object drawn at a certain point and move to the point that is touched on the screen. I am trying to use it for my game where when the user touches on the screen, the gun fires from the position of the player, but the player is stationary.
Thanks in advance.
P.S.
Is there a visual graphic of some sort that shows where every plot is on android.
I don't know what kind of library you're using to draw all of your things, but that basically doesn't matter since you only need to know two things in order to do this:
Without going into specifics on vector geometry:
1. You need to calculate the direction (x and y component) that the projectile moves in depending on your mouses position. You get this direction by simply subtracting the position of the mouse from the position of the player:
//x component of direction
float direction_x = mousePosition.x - playerPosition.x;
//y component of direction
float direction_y = mousePosition.y - playerPosition.y;
In order to just get a direction instead of adding a velocity component to this vector, you need to normalize it (so it has a length of 1):
float length =(float) Math.sqrt(direction_x*direction_x + direction_y*direction_y);
direction_x /= length;
direction_y /= length;
You then need to update the projectiles position by adding the direction_x and direction_y components to it, multiplied by the speed that you want the projectile to have (This process is called linear interpolation, by the way):
projectile_x += direction_x*speed;
projectile_y += direction_y*speed;
If you have some way of measuring the time between two frames, the speed variable should depend on the elapsed time between those frames, in order to create smooth movements on different platforms.

Categories

Resources