Java – how do I move entities to X and y?

I'm looking for a way to move my entity (bullet) to X and y, which is the player's position when the bullet is fired So in my physical class, I have –

float xSpeed = 1.0F;
   float ySpeed = 0.0F;

If I want to move an entity in a diaganal row, I will make XSPEED and yspeed = 1.0F. How can I move it in another X and Y directory?

Thank you for your help editing – yes, thank you for your help. For others who need help finding this problem, this is my code –

float xSpeed = 0;
    float ySpeed = 0;

Then I have some math to make them move at the same speed

ySpeed =  ySpeed * (float) (2.5 / Math.sqrt(xSpeed * xSpeed + ySpeed * ySpeed));
   xSpeed = xSpeed * (float) (2.5 / Math.sqrt(xSpeed * xSpeed + ySpeed * ySpeed));

And this code sets XSPEED and yspeed according to the X and y you want to move

xSpeed = (Game.PlayerX - x) / 3;
    ySpeed = (Game.Playery - y) / 3;

Then, finally, add XSPEED and yspeed to the X and y of the entity

this.x += xSpeed;
    this.y += ySpeed;

Solution

The usual method is to set relative X and Y speeds to cover the X and Y distances required in the allocated travel time:

float xSpeed = (targetLocation.x - currentLocation.x) / travelTime;
float ySpeed = (targetLocation.y - currentLocation.y) / travelTime;

If you want to travel at a predetermined speed instead of within a predetermined travel time, please set the above calculation and traveltime to an arbitrary value (1.0F works normally, so you can simply eliminate Division) Then calculate this factor:

float factor = desiredSpeed / Math.sqrt(xSpeed * xSpeed + ySpeed * ySpeed);

(note that if both XSPEED and yspeed are 0, they will be divided by zero, but this only means that the current position and target position are the same. If this is a possible condition, an appropriate check should be included.) Finally, readjust XSPEED and speed by this factor:

xSpeed *= factor;
ySpeed *= factor;

Note that by setting traveltime to 1, this is just a sneaky way to multiply the predetermined speed by the sine and cosine of the travel direction and the angle of the x-axis, not triangulation at all

The above is the Java compiled by programming house for you - how to move entities to X and y? I hope this article can help you solve Java - how to move entities to X and y? Program development problems encountered.

If you think the content of the programming home website is good, you are welcome to recommend the programming home website to programmers and friends.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>