火箭追踪中关于角度旋转控制的巧妙实现方法<30/10/2017>
先上效果图:
然后火箭的代码是:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(Rigidbody2D))]//如果火箭没有这个组件就自动给它加一个
public class HomingMissile : MonoBehaviour
{
public Transform target;
private Rigidbody2D rb;
void Start() { rb = GetComponent<Rigidbody2D>(); }
void FixedUpdate()
{
Vector2 direction = (Vector2)target.position - rb.position;
direction.Normalize();
float rotateAmount = Vector3.Cross(direction, -transform.up).z;//通过drection(存在正负变化)和transform.up前方向得到一个法向量的z值来确立角速度
print(rotateAmount);//该值在(-1,1)之间变化
rb.angularVelocity = rotateAmount * 200;//施加一个角速度的速率,方向越偏角速度越打转的越快
//rb.velocity = transform.up * 5;//施加一个向前方移动的速率,用来追踪
}
void OnTriggerEnter2D()
{
//撞击后自动销毁
Destroy(gameObject);
}
}