所以继承我的问题。我有一个盒子,我希望我的角色四处走动。但我希望能够在持有多个移动命令的同时移动它,例如.. 当向右移动(朝向障碍物的左侧)时,我希望能够同时向右或向上或向下移动,而角色不会粘在盒子上。有趣的是,它对于障碍物的左侧和右侧工作正常,但当我在障碍物的顶部和底部尝试时它会粘住。 下面是玩家类(物体移动)
<!-- 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中的更新方法
<!-- 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;
}
答案 0 :(得分:0)
我不确定定义偏移的位置,但我假设它是你刚刚制作该帧的动作。
你的问题是,因为你检查左和右在上下之前,如果你沿着对角线向下移动到盒子的顶部边缘,那么你将在Y方向上注册一个命中 - HitWall
不会检查你要去哪个方向,它只检查碰撞。因此,Y轴上的碰撞会在if (player.right && HitWall(player))
线上计算并停止横向移动。
最好的办法是应用你的侧身运动,检查击中,如果有的话再向后移动 - 然后应用向下运动,检查击中,如果有则向后移动。纠正这样的位置应该意味着你可以随意滑动。