1
\$\begingroup\$

I am writing a game in which I am representing a velocity with a vector. I have a starting point and a point that I want the object to move towards at a certain speed. (I need the resulting vector's x and y values to add up to 800). I'm not sure what kind of formula I can use to accomplish this.

SO! I have a starting point. An "ending point". And need a vector whose x and y values add up to 800.

Here is the code I came up with:

dx = size.width / 2 - ball.position.x
dy = 800 - size.height / 2 - ball.position.y
ball.physicsBody?.velocity = CGVectorMake(dx, dy)

Although this appears to work, |dx| + |dy| != 800 and therefore the balls move at slightly different speeds. I'm sure I'm doing this wrong, but I'm not sure how to go about fixing it.

\$\endgroup\$
0

1 Answer 1

1
\$\begingroup\$

If you want a velocity of 800, you actually don't want x and y to add up to 800, you wan't the vectors length to be 800.

If you already have the correct direction, you could normalize the vector, which would then be a unit-vector (length 1) and multiply this unit-vector by any scalar (number) you want to get the length you need, for example:

int neededLength = 800;
vec2 velocity = normalize(direction) * neededLength;

If you really want x + y to be 800, you would need something like this:

vec2 direction; //Your direction-vector
vec2 out = new vec2;
out.x = direction.x / (direction.x + direction.y) * 800;
out.x = direction.y / (direction.x + direction.y) * 800;
\$\endgroup\$
1
  • \$\begingroup\$ I just realized my code snippet doesn't make much sense out of context. "size" is the size of the screen. So I am basically launching the balls from one point to the center. I'd like them to move at a consistent starting speed. I guess I'm not really understanding CGVector in relation to velocity. \$\endgroup\$
    – FryDay
    Commented Mar 2, 2015 at 21:10

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .