14
$\begingroup$

I'm making a video game in which a ball is moving towards a player. So, I have a point $P$ describing the point where the player is, and a point $B$ describing where the ball is. I know that we can represent the direction from $B$ to $A$ as a vector.

I want to move the ball a small amount towards the player, along the direction of this vector. Is there a simple way to determine the new coordinates of the ball?

$\endgroup$
3
  • $\begingroup$ Where exactly are you running into problems? There's many ways to do this, but it depends on how computationally efficient you want the solution... $\endgroup$
    – apnorton
    Mar 18, 2013 at 1:11
  • $\begingroup$ I just want to move the collision point small distance in the direction of the player. Is there a way I can move the point along the vector? $\endgroup$ Mar 18, 2013 at 1:14
  • 1
    $\begingroup$ I've made substantial edits to this question, in hopes of triggering a reopoen vote. Because the question is 4 years old and my answer was accepted, I believe it is ok to take some liberty in interpreting the original post for clarity's sake. $\endgroup$
    – apnorton
    Apr 22, 2017 at 1:15

2 Answers 2

28
$\begingroup$

Let's say you have a vector $\vec P = [P_1, P_2, P_3]$ that represents the point's location in space. Another vector, $\vec B = [B_1, B_2, B_3]$ represents the ball's (or bullet's or whatever) position in space.

The vector $\vec {BP}$ between the two is: $$\vec{BP} = \vec P - \vec B = [P_1 - B_1, P_2- B_2, P_3-B_3]$$

So, if you want the ball to move all the way to the player, you would say: $$\vec B_{new} = \vec B + \vec{BP}$$

Or, if you want the ball to move only $1/100$th of the way to the player, you would say: $$\vec B_{new} = \vec B + \frac{1}{100}\vec{BP}$$

In general, to move some small $\epsilon$ to the player: $$\vec B_{new} = \vec B + \epsilon\vec{BP}$$

$\endgroup$
1
  • $\begingroup$ Thanks! so if you want to move the point just have add it to vector. Thank you! $\endgroup$ Mar 18, 2013 at 1:29
0
$\begingroup$

Alternatively, I'd find a linear function that connects a player with a ball:

$$ f(x) = ax + b \\ \iff \\ a = \frac{P_y-B_y}{P_x-B_x} \\ b = P_y - a \cdot P_x $$

To get new coordinates of the ball, we calculate normal vector length:

$$ \vert\vert v \vert\vert = \sqrt{1+a^2} $$

and use it to get x-translation - for every $n$ pixels run along our line:

$$ \vec{x} = \frac{n}{\vert\vert v \vert\vert} $$

For example, if ball has passed 10 pixels along our line:

$$ \vec{x} = \frac{10}{\sqrt{1+a^2}} $$

Finally, new coordinates of the ball are as follows:

$$ x' = x + \vec{x} \\ y' = f(x') $$

where $x$ is current x-position of the ball.

$\endgroup$

You must log in to answer this question.

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