不使用rigidbody 和collider的方式
直接上代码
代码
public class ThrownItem : MonoBehaviour
{
public Vector3 Velocity;
public LayerMask layer;
public Vector3 Gravity = Physics.gravity;
public bool active;
private Vector3 current_pos;//当前位置
private Vector3 start;
private float i = 1f;
//额外视觉效果 使模型可以旋转
public float rotateSpeed = 600f;
public Transform model;
Vector3 defaultRotate;
void Start()
{
start = transform.position;
current_pos = start;
if (model) defaultRotate = model.eulerAngles;
}
private void Update()
{
if (active)
{
model.Rotate(Vector3.right * rotateSpeed * Time.deltaTime, Space.Self);//在空中旋转
}
}
private void FixedUpdate()
{
CalculateThrownMove(Time.fixedDeltaTime);
}
/// <summary>
/// 核心计算
/// </summary>
void CalculateThrownMove(float tick)
{
if (active)
{
float time = tick * i;
var gravity = Gravity * time * time / 2;//计算重力
var nex = Velocity * time;//下一个位置
Vector3 next_pos = start + nex + gravity; //下一个位置
Debug.DrawLine(current_pos, next_pos, Color.yellow);
transform.position = current_pos;
if (Physics.Linecast(current_pos, next_pos, out RaycastHit hit, layer, QueryTriggerInteraction.Ignore))
{
model.eulerAngles = defaultRotate + new Vector3(Random.Range(1, 46), 0, 0); //更改旋转角度
active = false;
Debug.Log(hit.transform.name);//击中了 做一些判断
Destroy(gameObject, 5);
}
current_pos = next_pos;
i++; //很重要
}
}
}
测试脚本
public class ThrownPoint : MonoBehaviour
{
public ThrownItem item;
public Transform point;
public float powerMulti;
public Vector3 velocity;//46
float time;
public bool debug;
void Update()
{
//if (UnityEngine.Input.GetKey(KeyCode.Mouse0))
//{
// time += Time.deltaTime;
// velocity = transform.forward * powerMulti * time;
//}
if (UnityEngine.Input.GetKeyUp(KeyCode.Mouse0))
{
velocity = transform.forward * powerMulti;
var clone = Instantiate(item,transform.position,transform.rotation);
clone.Velocity = velocity;
clone.active = true;
velocity = Vector3.zero;
time = 0;
if (debug)
{
Debug.Break();
debug = false;
}
}
}
}
脚本挂载和使用
需要投掷的物体
测试发射点
拓展?
如果想实现一个击中后投掷物体弹开的的效果,可以在需要投掷的物体上挂载rigidbody和collider组件,初始时为禁用,当射线击中的时候,在打开对应的组件,然后再施加一个初始的velocity给rigidbody,这样就可以实现弹开的效果了.
希望对你有帮助
|