Codesnippets > 2D-snippets

Moving between two sets of coordinates

(1/3) > >>

MrTAToad:
This code allows you to calculate the X/Y step values between two sets of coordinates, allowing you to move between the two.


--- Code: (glbasic) ---// --------------------------------- //
// Project: TestLineMove
// Start: Monday, January 19, 2009
// IDE Version: 6.138

TYPE tMoveAlongLine
ax
ay
ex
ey
bx
by
ix
iy
numSteps
maxDistance
ENDTYPE

FUNCTION _dummy:
ENDFUNCTION

INLINE
#include "math.h"
extern double atan2 (      double y,      double x );
ENDINLINE

FUNCTION setTo:x,y
moveAlongLine.ax=x
moveAlongLine.ay=y
ENDFUNCTION

FUNCTION changeTo:bx,by
moveTo(moveAlongLine.ax,moveAlongLine.ay,bx,by)
ENDFUNCTION

FUNCTION angleBetweenPoints:ax,ay,ex,ey
INLINE
double angle;

angle=atan2(ex-ax,ey-ay);
if (angle<0.0)
{
angle=180.0+(180.0+angle);
}

return angle;
ENDINLINE
ENDFUNCTION

FUNCTION moveTo:sx,sy,fx,fy,mDistance=-1.0
LOCAL dx
LOCAL dy

moveAlongLine.ax=sx
moveAlongLine.ay=sy
moveAlongLine.ex=fx
moveAlongLine.ey=dy

dx=fx-sx
dy=fy-sy

moveAlongLine.bx=ABS(dx)
moveAlongLine.by=ABS(dy)

IF moveAlongLine.bx>moveAlongLine.by
moveAlongLine.numSteps=moveAlongLine.bx
ELSE
moveAlongLine.numSteps=moveAlongLine.by
ENDIF

moveAlongLine.maxDistance=mDistance
moveAlongLine.ix=dx/moveAlongLine.numSteps
moveAlongLine.iy=dy/moveAlongLine.numSteps
ENDFUNCTION

FUNCTION process%:speed
IF moveAlongLine.numSteps<=0.0
RETURN FALSE
ELSE
INC moveAlongLine.ax,moveAlongLine.ix*speed
INC moveAlongLine.ay,moveAlongLine.iy*speed
DEC moveAlongLine.numSteps,speed

IF moveAlongLine.maxDistance>0.0
DEC moveAlongLine.maxDistance,speed
IF moveAlongLine.maxDistance<=0.0
moveAlongLine.numSteps=0.0
moveAlongLine.maxDistance=0.0
RETURN FALSE
ENDIF
ENDIF
ENDIF

RETURN TRUE
ENDFUNCTION

--- End code ---

The angle between two points code needs changing as its inaccurate, but the rest works fine.

The test code :


--- Code: (glbasic) ---GLOBAL moveAlongLine AS tMoveAlongLine

SETSCREEN 1024,768,0
moveTo(0,0,200,100)
DEBUG "Angle : "+angleBetweenPoints(100,100,10,20)+"\n"

WHILE TRUE
DEBUG "X:"+moveAlongLine.ax+"\n"
DEBUG "Y:"+moveAlongLine.ay+"\n"
DEBUG moveAlongLine.numSteps+"\n"
DRAWLINE moveAlongLine.ax,moveAlongLine.ay,1,1,RGB(255,255,255)
SHOWSCREEN
process(0.25)
WEND
--- End code ---

If anyone has a better routine for calculating the angle between two coordinates, let me know :)

Kitty Hello:
why inline? Why ATAN2? The GLBasic ATAN _is_ atan2.

Moru:
Mabe this should be in the manual, MrTAToad here isn't the first to ask this. I was too slow to answer him on IRC though.

MrTAToad:
I had thought ATAN2 would compile, but alas, its not found.

Schranz0r:
ATAN == ATAN2 !


And works fine ;)

Navigation

[0] Message Index

[#] Next page

Go to full version