感觉自己对物理运算真的不太理解 这两天学习过程当中看到有大佬写了个实用技能 叫求物体碰撞墙体后的反射角 ,随后朝反射角的方向移动 就有点像模拟真实世界的碰撞反弹,感觉挺有意思的,记录一下学习过程。
本来以为挺难的 ,没有接触过这种,但是发现其实主要用的是Unity的一个API ,叫做 Vector3.Reflect(Vector3 inDirection, Vector3 inNormal)。 顾名思义就是求反射角,这里面的参数 一个是入射角的方向,一个是碰撞到的平面的法向量,返回的是求得的反射角。
新建一个场景,随便搭几个cube缩放一下形成墙体,然后准备个胶囊体,身上需要挂载组件:Rigidbody (发生碰撞的必要条件,不用多说)。
这里的几个墙体都设置了一个新的Tag:Obstacles。因为检测到地面是不需要反弹的,所以加上反弹条件。
脚本也挺简单,直接贴上:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
Rigidbody rigidbody;
Vector3 dir;
float speed = 5;
// Start is called before the first frame update
void Start()
{
rigidbody = GetComponent<Rigidbody>();
dir = new Vector3(Random.Range(-1f, 1f), 0, Random.Range(-1f, 1f)).normalized;
}
// Update is called once per frame
void FixedUpdate()
{
rigidbody.MovePosition(transform.position + dir * speed * Time.deltaTime);
}
private void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.CompareTag("Obstacles"))
{
var direction = Vector3.Reflect( dir, collision.GetContact(0).normal).normalized;
direction.y = 0;
dir = direction;
}
}
}
把脚本挂载到胶囊体,运行效果如下: