来自《Unity和C#游戏编程入门第五版》
PhysX引擎介绍
1.Rigidbody(刚体)组件:为物体增加Mass(质量)、Drag(阻力)等属性,使物体受如重力等力的影响。
2.Collider(碰撞体)组件:决定物体如何进入或离开其他物体的物理空间,即物体碰撞时的交互结果。
刚体运动实践
通过物理系统施加力有两种方法,一是Rigidbody类提供的AddForce()和AddTorque()方法,分别移动、旋转物体(力和扭矩)。二是Rigidbody类提供的MovePosition()和MoveRotation()方法,与前者的区别在于在调用这两种方法时,系统会自动在幕后处理好边界情况。
代码:
新增了Rigidbody类型变量_rb在Start()方法内绑定Player的Rigidbody组件。注意,任何与物理相关的代码都要放到FixedUpdate()方法中,FixedUpdate()方法独立于帧率,适用于所有物理代码。新增了Vector3变量rotation用于存储左右旋转值,新增了Quaternion变量angleRot将Vector3参数转换为以欧拉角为单位的旋转值并存储。最后使用Rigidbody类的MovePosition()和MoveRotation()方法实现物体的刚体运动。
using UnityEngine;
public class PlayerBehavior : MonoBehaviour
{
public float moveSpeed = 10f;
public float rotateSpeed = 75f;
private float vInput;
private float hInput;
private Rigidbody _rb;
void Start()
{
_rb = this.GetComponent<Rigidbody>();
}
void Update()
{
vInput = Input.GetAxis("Vertical") * moveSpeed;
hInput = Input.GetAxis("Horizontal") * rotateSpeed;
/*this.transform.Translate(Vector3.forward * vInput * Time.deltaTime);
this.transform.Rotate(Vector3.up * hInput * Time.deltaTime);*/
}
void FixedUpdate()
{
Vector3 rotation = Vector3.up * hInput;
Quaternion angleRot = Quaternion.Euler(rotation * Time.fixedDeltaTime);
_rb.MovePosition(this.transform.position + this.transform.forward * vInput * Time.fixedDeltaTime);
_rb.MoveRotation(_rb.rotation * angleRot);
}
}
碰撞体和碰撞实践
物体表面的绿色的线表示碰撞体的Capsule Collider,可以通过Inspector面板上的Center、Radius、Height这些属性对其进行移动和缩放。碰撞体默认与原始对象形状匹配。
代码
内容简单就不解释了
using UnityEngine;
public class ItemBehavior : MonoBehaviour
{
void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.name == "Player")
{
Destroy(this.gameObject);
Debug.Log("Item collected!");
}
}
}
遇上的问题:
以前给了血包一个旋转的动画,现在有给血包了一个刚体组件,导致运行时血包受重力影响在地上不断翻滚移动,后来发现问题后,在Inspector面板取消了血包使用重力的勾选: