Game math (distance increments) [Archive] - C Board

PDA

View Full Version : Game math (distance increments)


jdinger
03-25-2002, 11:52 AM
I have 2 points (start, end) represented by POINTS (ptStart, ptEnd). The 2 points represent the barrel of the players gun and the target, respectively (it's a 2d iso game).

I know that to get the distance between the points I would use:

distance = sqrt(((ptEnd.x-ptStart.x)*(ptEnd.x-ptStart.x))+((ptEnd.y-ptStart.y)*(ptEnd.y-ptStart.y)))

What I don't know is how to figure the incremental amounts added/subtracted to the original point to move the object to the end point. Unless my end point is and equal distance from my start x AND y, I can't just increment through the distance.

What I'm looking for is a smooth transition from point a to point b. I just don't know what to add/subtract in my loop to get it.

Thanks in advance for any help you can give.

Barjor
03-25-2002, 12:14 PM
Lets see if I can explain this..I'll give it a try ask me again if I don't get it clear

Y = KX + M (Standard linear equation)

deltaY = EndY - StartY
deltaX = EndX - StartX

K = deltaY / deltaX

You know know the K value for your line. We now need to know M

M = Y - KX (Standard linear equation)
M = StartY - K*StartX

You can now increment your X value from start to end and get the Y value for your linear curve by using Y =KX + M

jdinger
03-25-2002, 01:36 PM
That doesn't work (unless I misunderstood something, which is quite possible).

Here's the code:


POINT ptStart, ptEnd, ptMob;

DeltaX = ptEnd.x - ptStart.x
DeltaY = ptEnd.y - ptStart.y
K = DeltaY / DeltaX
M = ptStart.y - K * ptStart.x
Y = K * ptStart.x + M
ptMob.x = ptMob.x + 1
ptMob.y = ptMob.y + K


With the following initial settings:

ptStart.x = 5
ptStart.y = 200
ptEnd.x = 200
ptEnd.y = 20
ptMob.x = ptStart.x
ptMob.y = ptStart.y

It gives me this:
DeltaX = 195
DeltaY = -180
K = -1
M = 205
Y = 200

Barjor
03-25-2002, 03:18 PM
-180/195 is not -1. You can't use int. cast to double. The method I oulined will also give you problem with perfectly vertical and horizontal lines so you have to test for those two cases if(DeltaX == 0 || DeltaY == 0) before you solve the linear equation

Bubba
03-25-2002, 03:30 PM
If you look at his math for a second you will realize that it is the old y=mx+b from school.


A line is a linear interpolation between y and y2 and a linear interpolation between x or x2 or a bi linear interpolation of x,x2,y,y2.

Barjor
03-25-2002, 03:33 PM
Is there a better way to do this? I don't like the way that it works with vertical lines. It feals like a kludge.

jdinger
03-25-2002, 03:47 PM
Originally posted by Barjor
[B]-180/195 is not -1. You can't use int. cast to double.

I'm using 2d coords (screen x,y). Are you saying to cast to double and then convert and use just the int portion? Would that give accurate enough results?


*kicks self*
Now I wish I would have paid better attention in high school (unless I did and I'm just too old to remember!) :D