这就是我的问题。我有一个盒子,我想让我的角色四处移动。例如,我希望能够在按住多个移动命令的同时移动它。当向右移动(朝向障碍物的左边)时,我希望能够同时按住向右移动和向上或向下移动,而不会让角色粘在方框上。有趣的是,它在障碍物的左侧和右侧都能正常工作,但当我在障碍物的顶部和底部尝试它时,它就会卡住。这是Player类(对象我在移动)
<!-- language: c# -->
public class Player
{
public Texture2D texture;
public Vector2 position;
public int speed;
public Vector2 offset;
public bool left, right, up, down;
public Rectangle collisionRect
{
get
{
return new Rectangle((int)position.X , (int)position.Y, texture.Width, texture.Height);
}
}
public Vector2 direction;
public Player(Texture2D texture, Vector2 position, int speed)
{
this.texture = texture;
this.position = position;
this.speed = speed;
offset.X = speed;
offset.Y = speed;
left = false;
right = false;
up = false;
down = false;
}
public virtual void Update(GameTime gameTime, Rectangle clientBounds)
{
direction = Vector2.Zero;
if (Keyboard.GetState().IsKeyDown(Keys.A))
{
direction.X -= 1;
left = true;
}
else
left = false;
if (Keyboard.GetState().IsKeyDown(Keys.D))
{
direction.X += 1;
right = true;
}
else
right = false;
if (Keyboard.GetState().IsKeyDown(Keys.W))
{
direction.Y -= 1;
up = true;
}
else
up = false;
if (Keyboard.GetState().IsKeyDown(Keys.S))
{
direction.Y += 1;
down = true;
}
else
down = false;
position += (direction * speed);
}
public virtual void Draw(GameTime gameTime, SpriteBatch spritebatch)
{
spritebatch.Draw(texture, collisionRect, Color.White);
}
}
下面是我的maingame中的Update方法
<!-- language: c# -->
public override void Update(GameTime gameTime)
{
// TODO: Add your update code here
player.Update(gameTime, Game.Window.ClientBounds);
if (player.right && HitWall(player))
{
player.position.X -= player.offset.X;
}
else if (player.left && HitWall(player))
{
player.position.X += player.offset.X;
}
if (player.down && HitWall(player))
{
player.position.Y -= player.offset.Y;
}
else if (player.up && HitWall(player))
{
player.position.Y += player.offset.Y;
}
base.Update(gameTime);
}
和HitWall函数
<!-- language: c# -->
public bool HitWall(Player player)
{
for (int i = player.collisionRect.Top; i < player.collisionRect.Bottom; i++)
for (int j = player.collisionRect.Left; j < player.collisionRect.Right; j++)
if (TextureData[i * gameMap.map.Width + j] != Color.White)
return true;
return false;
}
发布于 2012-03-22 15:32:41
我不确定偏移量是在哪里定义的,但我假设它是你刚刚做的那个帧的运动。
你的问题是,因为你在上下移动之前检查了left & right,如果你沿对角向下移动到盒子的顶部边缘,那么你会在Y方向上记录一个命中,- HitWall
不会检查你要去的方向,它只会检查是否有碰撞。因此,Y轴上的碰撞在线if (player.right && HitWall(player))
上计数,并停止横向移动。
最好的办法是应用您的横向移动,检查是否有命中,如果有一个- then,则向后移动应用您的向下移动,检查是否有命中,如果有则向后移动。像这样纠正位置应该意味着你可以随心所欲地沿着两边滑动。
https://stackoverflow.com/questions/9818005
复制相似问题