假设以固定速度将A点(x1,y1)移动到位置(x2,y2),比如每秒3个单位(点)。
要求是A点只能在x或y轴上移动。
例如,A(0,0)以3单位/秒的速度移动到目标(10,10)。首先在x轴上开始移动,1秒后,A的位置变为(3,0)。然后在3秒后变为(9,0)。现在在x轴上,A只需要移动1个单位,然后在y轴上移动2个单位,变为(10,2),然后在y轴上继续,(10,5)...(10 ,8)
我的问题是:有没有有效的方法来实现这一目标?这是我的逻辑:
while(the point is not arriving the target point) {
currentX = SourceX;
currentY = SourceY;
differenceOnXaxis=TargetX-currentX;
differenceOnYaxis=TargetY-currentY;
if(differenceOnXaxis == 0) {
if(differenceOnYaxis == 0) {
//Arrive at the target point
} else if (differenceOnYaxis >= MovingUnit){
currentY += MovingUnit;
} else if (0 <differenceOnYaxis < MovingUnit){
currentY += differenceOnYaxis;
} else if (-MovingUnit <differenceOnYaxis < 0) {
currentY += differenceOnYaxis;
} else if (differenceOnYaxis<= (-MovingUnit)) {
currentY -= MovingUnit;
}
} else if(differenceOnXaxis >= MovingUnit){
currentX += moving unit;
} else if (0< differenceOnXaxis < MovingUnit) {
currentX += differenceOnXaxis;
if(differenceOnYaxis > 0){
currentY += (MovingUnit - differenceOnXaxis)
} else if (differenceOnYaxis < 0) {
currentY += -(MovingUnit-differenceOnXaxis)
}
} else if (- MovingUnit < differenceOnXaxis < 0) {
currentX += differenceOnXaxis;
} else if (differenceOnXaxis <= (-MovingUnit)) {
currentX -= MovingUnit;
}
}