直接上代码:
叉乘实现: 判断左右 能做到看向
void Update()
{
a = transform.forward;
b = (target.position - transform.position).normalized;
Vector3 crossValue = Vector3.Cross(a, b);
Debug.Log(crossValue);
if (crossValue.y >= 0)
{
transform.Rotate(Vector3.up, 0.5f);
}
if (crossValue.y < 0)
{
transform.Rotate(Vector3.up, -0.5f);
}
}
点乘实现, 判断前后 能做到forward与target所在方位垂直.
void Update()
{
a = transform.forward.normalized;
b = (target.position - transform.position).normalized;
float dotValue = Vector3.Dot(a, b);
//float angle = Mathf.Acos(dotValue) * Mathf.Rad2Deg;
Debug.Log(dotValue);
if (dotValue > 0)
{
transform.Rotate(Vector3.up, 0.5f);
}
if (dotValue < 0)
{
transform.Rotate(Vector3.up, -0.5f);
}
}
使用joystick进行移动。
法1:
/// <summary>
/// 1.求出forwad的夹角 2.旋转向量
/// </summary>
/// <param name="v2"></param>
/// <returns></returns>
private void MoveAlongWithHead(Vector2 axis, float speed = 1f)
{
Vector3 cross = Vector3.Cross(transform.forward, head.forward);
float angle = Vector3.Angle(transform.forward, head.forward);
angle = cross.y < 0 ? -angle : angle;
Vector3 dir = Quaternion.Euler(0, angle, 0) * new Vector3(axis.x, 0, axis.y).normalized;
rb.MovePosition(transform.position + dir * speed * Time.fixedDeltaTime);
}
法2:
private void MoveAlongWithHead(Vector2 axis, float stepLength)
{
Vector3 headLookAt = head.forward;
Vector3 headLookAtNormalized = Vector3.ProjectOnPlane(headLookAt, new Vector3(0, 1, 0));
headLookAtNormalized = headLookAtNormalized.normalized;
Vector3 axis3D = (new Vector3(axis.x, 0, axis.y)).normalized;
Quaternion q = Quaternion.LookRotation(headLookAtNormalized);
axis3D = q * axis3D;
transform.position = transform.position + axis3D * stepLength * Time.fixedDeltaTime;
//Debug.DrawLine(head.transform.position, head.transform.position + axis3D * 10, Color.red);
}
eg:Quaternion实现lookat, v3(自己) - v3(target)
transform.rotation = Quaternion.LookRotation(transform.position - Camera.main.transform.position);