我让玩家朝着我点击的地方移动。但当我到达我点击的位置时,精灵只是来回闪烁。我假设它是因为精灵正在经过这一点,回到它,再次经过它,然后不断创造一个'闪烁'。有什么想法吗?
的 的 **** 解决的 * ** < EM> * **** ** * 更新后的代码 * **
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
namespace AsteroidAvoider
{
class Player
{
public Vector2 position, distance, mousePosition;
public float speed;
public float rotation;
public Texture2D playerImage;
public MouseState mouseState;
public Player(Texture2D playerImage, Vector2 position, float speed)
{
this.playerImage = playerImage;
this.position = position;
this.speed = speed;
}
public void Update(GameTime gameTime)
{
mouseState = Mouse.GetState();
float speedForThisFrame = speed;
if (mouseState.LeftButton == ButtonState.Pressed)
{
mousePosition.X = mouseState.X;
mousePosition.Y = mouseState.Y;
}
if ((mousePosition - position).Length() < speed)
speedForThisFrame = 0;
if ((mousePosition - position).Length() > speed)
speedForThisFrame = 2.0f;
distance = mousePosition - position;
distance.Normalize();
rotation = (float)Math.Atan2(distance.Y, distance.X);
position += distance * speedForThisFrame;
}
public void Draw(SpriteBatch spriteBatch)
{
spriteBatch.Draw(playerImage, position, null, Color.White, rotation, new Vector2(playerImage.Width / 2, playerImage.Height / 2), 1.0f, SpriteEffects.None, 1f);
}
}
}
答案 0 :(得分:1)
你需要一个碰撞器,一个代表你的玩家的Rectangle
,所以当这个碰撞器包含你的mousePosition
或点击坐标(你可以使用Rectangle.Contains
方法轻松检测到它)时,你只需要将玩家的速度设置为0,避免闪烁。
当然,当点击的坐标发生变化时,你必须设置前一个玩家的速度。
答案 1 :(得分:1)
标准化向量,如果我没记错的话应该总长度为1(Vector2.Length()返回整个vector2的长度) 一个简单的解决方案是让你的单位在鼠标范围内降低移动速度,例如
float speedForThisFrame = speed;
if((mousePosition-position).Length() < speed) speedForThisFrame = (mousePosition-position).Length();
并使用speedForThisFrame进行位置偏移。