我正在制作一个等距游戏(钻石网格),我偶然发现了一个关于角色运动的小问题。
我使用A *找到2点之间的路径,然后我想将我的角色从A点移动到B点,经过形成路径的所有瓷砖,但我找不到这样做的方法,我的意思是一种更简单准确的方法。
到目前为止,我已经废弃了这段代码,但它有点生锈了#34;
public void Destination(tile destination)
{
for (int i = 0; i < 8; i++)
{
if (AdjacentTile[i] == destination)
{
characterDirection = i;
}
}
animation.changeSpriteDirection(characterDirection); //After I found which adjacent tile is the next destination I change the character direction based on it's position (1 = North , 2 = Nort Est etc) .. so the Y of the Animation_sourceRectangle it's changed//
Vector2 Position;
Position.X = current_characterTile.X - destination.X;
Position.Y = current_characterTile.Y - destination.Y;
rotation = (float)Math.Atan2(-Position.X, Position.Y);
moveVector = (Vector2.Transform(new Vector2(0, -1), Matrix.CreateRotationZ(rotation))) * characterSpeed;
movingCommand = 1; // the character is supposed to be moving..
Move(); //this function moves the sprite until the *tile.i and tile.j* of the character is the same as tile.j and tile.i of the destination
//something like this
if ( characterTile.i == destination.i && characterTile.j == destination.j)
movingCommand = 0 //stop
else
character_Position += moveVector;
}
如果有人能给我一些关于做什么或帮助我的提示,我将非常感激。
谢谢。
答案 0 :(得分:1)
<强>可能性:强>
解决方案:
假设您已经运行了寻路算法,并找到了一个必须经过的瓦片的链接列表才能到达目标。我们还假设这些图块不会在运动的中途被阻挡(尽管如此,修改算法很简单。)
我通常会做这样的事情来处理这个问题:
beginMovingToTarget()方法将确定速度矢量,并确定到达图块所需的时间。到达时间后,我们立即转到下一个图块,直到路径为空。我们把这个时间变量称为character.timeToArrival。
更新():
if (!character.Moving) return; // Or just don't execute the rest of this code.
character.position += character.speed * elapsedSeconds;
character.timeToArrival -= elapsedSeconds;
// Did the character arrive in a tile?
if (character.timeToArrival <= 0)
{
// This will ensure the character is precisely in the tile, not a few pixels veered off.
character.position = character.movingToTile.position;
if (character.Path.Count == 0)
{
character.Moving = false;
// We are at final destination.
}
else
{
character.beginMovingToTarget(character.Path[0]);
character.Path.RemoveAt(0);
}
}
beginMovingToTarget(targetTile)函数:
this.movingToTile = targetTile;
Vector2 direction;
direction = targetTile.position - this.position;
this.timeToArrival = direction.Length() / this.speedPerSeconds;
direction.Normalize();
direction *= this.speedPerSeconds;
this.speed = direction;
// Here, you may also want to change the character's animation, if you want to, or you may do that directly in the Draw() method based on its speed vector.
确保除法是浮点数,而不是整数。