Recently wrote the RPG, found in the role of the movement of the object can still be a lot of mathematics before the knowledge (manager of all kinds of tangled brain repair), long time no blog, hot summed up the algorithm ideas, lest oneself after two days and forget.
known role speed and destination, for each frame position
We already know a character. Bodya speed to pixels per second
Float speed = 5
Destination is point destination
Current location is point currentposition = Bodya.getposition ()
So how do you calculate the current position of the character in the frame loop?
Scenario 1. Low computational weight, but not precise
VEC2 VEC = destination-currentposition;
Vec.normalize (); Unit of
Point nextposition = VEC * speed + currentposition
Scenario 2: The motion rotation function rotatebyangle Accurate, the computation quantity is big
Parameter 1. Role Current Location
Parameter 2. Speed vector
Parameter 3. Speed
Return: starting at point StartPoint, move the point of a range of pixels along a vector direction
Inline point getpointalongdirection (Point StartPoint, Vec2 dir, float range)
{
float radians = vec.getangle (VEC2 (0,1)); Clockwise is positive, counter-clockwise negativePoint Zerodegreepos = startPoint;Zerodegreepos.y = startpoint.y + range;Point Des2 = Zerodegreepos.rotatebyangle (StartPoint,-radians),//negative clockwise rotation
}
Scenario 3. On the idea of scenario 2, optimize the algorithm by vector formula
Use the vector collinear formula and the vector formula to push to:
the geometric representation of a vector collinear:
Set, wherein, when and only then, the vector collinear.
(1) if, then;
(2) if, then.
Parameter 1. Role Current Location
Parameter 2. Speed vector
Parameter 3. Speed
return: starting at point StartPoint, move the point of a range of pixels along a vector directionInline Point getpointalongdirection (Point StartPoint, Vec2 dir, float range){assert (range > 0);dir.normalize ();float x1 = dir.x;float y1 = dir.y;
float factor = sqrt (1/(x1 * x1 + y1 * y1)) * range;float x2 = factor * x1;float y2 = factor * y1;
Point des = startPoint; des . x + = x2; des . y + = y2;
return des;}
Original address
http://write.blog.csdn.net/postedit/47190919
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
One of the simple and practical algorithms of RPG based on COCOS2DX-the movement of characters