1

我让玩家向我点击的地方移动。但是当我到达我点击的位置时,精灵只是来回闪烁。我假设它是因为精灵正在超越这一点,回到它,再次超越它,然后不断地回去创造一个“闪烁”。任何想法为什么?

****已解决* ** * **** ** *更新代码* **

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);
        }
    }
}
4

2 回答 2

1

你需要一个碰撞器,aRectangle代表你的玩家,所以当这个碰撞器包含你的mousePosition或点击坐标时(你可以很容易地使用Rectangle.Contains方法检测它)你只需将玩家的速度设置为 0,避免闪烁。

当然,当点击的坐标发生变化时,你必须设置前一个玩家的速度。

于 2013-10-13T23:46:47.540 回答
1

如果我没记错的话,归一化向量的总长度应该始终为 1(顺便说一下,Vector2.Length() 返回整个向量2的长度)一个简单的解决方案是让你的单位在范围内降低移动速度例如鼠标

float speedForThisFrame = speed;
if((mousePosition-position).Length() < speed) speedForThisFrame = (mousePosition-position).Length();

并使用 speedForThisFrame 进行位置偏移。

于 2013-10-14T00:44:22.857 回答