Skip to content

Instantly share code, notes, and snippets.

@chaosddp
Last active August 29, 2015 14:08
Show Gist options
  • Save chaosddp/8ceb49cac442c808bd63 to your computer and use it in GitHub Desktop.
Save chaosddp/8ceb49cac442c808bd63 to your computer and use it in GitHub Desktop.
Make the entity move to current mouse pointer
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WaveEngine.Common.Math;
using WaveEngine.Framework;
using WaveEngine.Framework.Graphics;
using WaveEngine.Framework.Services;
namespace Share.Behaviors
{
public class MoveToPointerBehavior : Behavior
{
public MoveToPointerBehavior(float speed = 10f)
{
_speed = speed;
}
//使用RequiredComponent就可以不必自己从entity中取组件
[RequiredComponent]
private Transform2D _transform = null;
private Input _input;
private float _speed = 0f;
protected override void Initialize()
{
base.Initialize();
_input = WaveServices.Input;
}
protected override void Update(TimeSpan gameTime)
{
var mousePosition = new Vector2(_input.MouseState.X, _input.MouseState.Y);
var currentPosition = new Vector2(_transform.X, _transform.Y);
// 向量计算,得出方向
var dir = mousePosition - currentPosition;
// 如果亮点距离小于10,咱就不动了
if (dir.Length() < 10.0f) return;
// 计算角度
var angle = (float)(Math.Atan2(dir.Y, dir.X));
// 把速度在x,y轴上分解
_transform.X += (float)Math.Cos((double)angle) * _speed;
_transform.Y += (float)Math.Sin((double)angle) * _speed;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment