Created
August 4, 2018 08:57
-
-
Save huiliu/73834d52b8f49115ad2cb0d696071542 to your computer and use it in GitHub Desktop.
Unity3d控制移动方向做圆周运动
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Collections; | |
using System.Collections.Generic; | |
using UnityEngine; | |
public class Move | |
: MonoBehaviour | |
{ | |
[SerializeField] private Vector3 Anchor; | |
[SerializeField] private float Radius; | |
[SerializeField] private float Velocity; | |
// Use this for initialization | |
private float SquaredRadius; | |
void Start () | |
{ | |
this.SquaredRadius = this.Radius * this.Radius; | |
var v = new Vector3(-1, -1, 0); | |
Debug.Log(string.Format("{0} {1} {2} {3} {4} {5}", | |
Mathf.Atan2(1, 1) * 180/Mathf.PI, | |
Mathf.Atan2(-1, 1) * 180/Mathf.PI, | |
Mathf.Atan2(-1, -1) * 180/Mathf.PI, | |
Mathf.Atan2(1, -1) * 180/Mathf.PI, v.Rotate(89), v.Rotate(-89))); | |
} | |
// Update is called once per frame | |
void Update () | |
{ | |
var dir = GetInputDirection(); | |
if (dir == Vector3.zero) | |
return; | |
var p = transform.position; | |
var v = Anchor - p; | |
var dot = Vector2.Dot(dir, v); | |
var angleV = Mathf.Atan2(v.y, v.x); | |
if (dir != Vector3.zero && dot <= 0 && (p - Anchor).sqrMagnitude >= this.SquaredRadius) | |
{ | |
var angle = v.ToVector2().Cross(dir) >= 0 ? 89 : -89; | |
var c = v.ToVector2().Cross(dir); | |
if (c > 0.1f) | |
{ | |
angle = 89; | |
dir = v.Rotate(angle); | |
} | |
else if (c < -0.1f) | |
{ | |
angle = -89; | |
dir = v.Rotate(angle); | |
} | |
else | |
{ | |
v = Vector3.zero; | |
angle = 0; | |
dir = Vector3.zero; | |
} | |
} | |
Debug.Log(string.Format("move dir: {0}", dir)); | |
var targetPos = p + dir * this.Velocity * Time.deltaTime; | |
Debug.DrawLine(p, targetPos, Color.blue, 3.0f); | |
transform.position = targetPos; | |
} | |
private Vector2 GetNewDirection(Vector2 pos, Vector3 dir) | |
{ | |
return dir.Rotate(89); | |
} | |
private Vector3 Direction = Vector3.zero; | |
private Vector3 GetInputDirection() | |
{ | |
this.Direction.x = Input.GetAxis("Horizontal"); | |
this.Direction.y = Input.GetAxis("Vertical"); | |
return Direction.normalized; | |
} | |
} | |
public static class Utils | |
{ | |
public static Vector3 Rotate(this Vector3 v, float angle) | |
{ | |
float originRadian = (float)Mathf.Atan2(v.y, v.x); | |
float rotateRadian = (float)(angle * Mathf.PI / 180f); | |
float dstRadian = originRadian + rotateRadian; | |
return new Vector2((float)Mathf.Cos(dstRadian), (float)Mathf.Sin(dstRadian)) * v.magnitude; | |
} | |
public static float Cross(this Vector2 a, Vector2 b) | |
{ | |
return a.x * b.y - a.y * b.x; | |
} | |
public static Vector2 ToVector2(this Vector3 v) | |
{ | |
return v; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment