using UnityEngine;
public class TestSpeed : MonoBehaviour
{
public float time = 3; // 代表从A点出发到B经过的时长
public Transform pointA; // 点A
public Transform pointB; // 点B
public float g = -10; // 重力加速度
private Vector3 speed; // 初速度向量
private Vector3 Gravity; // 重力向量
private float dTime = 0; // 时间线 (一直在增长)
void Start()
{
// 将物体置于A点
transform.position = pointA.position;
// 通过一个式子计算初速度
speed = new Vector3(
(pointB.position.x - pointA.position.x) / time,
(pointB.position.y - pointA.position.y) / time - 0.5f * g * time,
(pointB.position.z - pointA.position.z) / time);
// 重力初始速度为0
Gravity = Vector3.zero;
}
private float MoveTime = 0;
void Update()
{
MoveTime += Time.deltaTime;
// 重力模拟
Gravity.y = g * (dTime += Time.deltaTime);
// 模拟位移
transform.Translate(speed * Time.deltaTime);
transform.Translate(Gravity * Time.deltaTime);
if (MoveTime>= time)
{
this.gameObject.SetActive(false);
}
}
}
using UnityEngine;
using System.Collections;
public class Radar : MonoBehaviour
{
public GameObject target;
public float speed = 10;
private float distanceToTarget;
private bool move = true;
void Start()
{
distanceToTarget = Vector3.Distance(this.transform.position, target.transform.position);
StartCoroutine(Shoot());
}
IEnumerator Shoot()
{
while (move)
{
Vector3 targetPos = target.transform.position;
//朝向目标 (Z轴朝向目标)
this.transform.LookAt(targetPos);
//根据距离衰减 角度
float angle = Mathf.Min(1, Vector3.Distance(this.transform.position, targetPos) / distanceToTarget) * 45;
//旋转对应的角度(线性插值一定角度,然后每帧绕X轴旋转)
this.transform.rotation = this.transform.rotation * Quaternion.Euler(Mathf.Clamp(-angle, -42, 42), 0, 0);
//当前距离目标点
float currentDist = Vector3.Distance(this.transform.position, target.transform.position);
if (currentDist < 0.3f)
{
move = false;
}
//平移 (朝向Z轴移动)
this.transform.Translate(Vector3.forward * Mathf.Min(speed * Time.deltaTime, currentDist));
yield return null;
}
}
}
using System;
using System.Collections;
using UnityEngine;
public class Bullet : MonoBehaviour
{
public GameObject target; //要到达的目标
public float speed = 10; //速度
private float distanceToTarget; //两者之间的距离
private bool move = true;
void Start()
{
//计算两者之间的距离
distanceToTarget = Vector3.Distance(this.transform.position, target.transform.position);
StartCoroutine(StartShoot());
}
IEnumerator StartShoot()
{
while (move)
{
Vector3 targetPos = target.transform.position;
//让始终它朝着目标
this.transform.LookAt(targetPos);
//计算弧线中的夹角
float angle = Mathf.Min(1, Vector3.Distance(this.transform.position, targetPos) / distanceToTarget) * 45;
this.transform.rotation = this.transform.rotation * Quaternion.Euler(Mathf.Clamp(-angle, -42, 42), 0, 0);
float currentDist = Vector3.Distance(this.transform.position, target.transform.position);
if (currentDist < 0.5f)
move = false;
this.transform.Translate(Vector3.forward * Mathf.Min(speed * Time.deltaTime, currentDist));
yield return null;
}
}
}