Jack Patrick - 16 days ago 7x

Java Question

I am looking for a way to make my Entity(A bullet) move towards a x and y,which is where the player was when the bullet was fired. so In my entity class i have -

`float xSpeed = 1.0F;`

float ySpeed = 0.0F;

if I wanted to move the entity in a diaganal line I would make xSpeed and ySpeed = 1.0F

How would I make it move in the dir of another x and y?

Thanks for the help

EDIT --

Solved,thanks for the help

To anyone else who finds this question needing help,here is my code-

`float xSpeed = 0;`

float ySpeed = 0;

then I have some maths to make it so they 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 to set the xSpeed and ySpeed,based on a x and y you want to move towards

`xSpeed = (Game.PlayerX - x) / 3;`

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

and then,finaly,add xSpeed and ySpeed to the x and y of your entity

`this.x += xSpeed;`

this.y += ySpeed;

Answer

The usual way is to set the relative x and y speeds to cover the required x and y distances in the allotted 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, rather than in a predetermined travel time, do the above computations with `travelTime`

set to some arbitrary value (`1.0f`

would work fine, so you could simply eliminate the division). Then compute this factor:

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

(Note that you'll be dividing by zero if `xSpeed`

and `ySpeed`

are both `0`

, but that simply indicates that the current and target locations are identical. If that's a possible condition, you should include an appropriate check.) Finally, readjust `xSpeed`

and `ySpeed`

by the factor:

```
xSpeed *= factor;
ySpeed *= factor;
```

Note that by setting `travelTime`

to `1`

, this is just a sneaky way of multiplying the predetermined speed by the sine and cosine of the angle that the travel direction makes with the x axis without mentioning trigonometry at all. :)

Source (Stackoverflow)

Comments