【发布时间】:2021-09-06 06:37:39
【问题描述】:
所以基本上我统一创建了一个简单的 3d 场景,但我的“角色”不断从物体中跌落或穿过它们,我尝试了每种类型的对撞机(网格、盒子、地形),甚至尝试为每个物体添加刚体组件,但是它没有成功
这是我让“角色”移动的代码
public class PlayerMovement : MonoBehaviour
{
//
public CharacterController controller;
public float speed = 12f;
public float gravity = -19.8f;
public float jumpHeight = 3f;
public Transform groundCheck;
public float groundDistance = 0.4f;
public LayerMask groundMask;
Vector3 velocity;
bool isGrounded;
// Update is called once per frame
void Update()
{
isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);
if(isGrounded && velocity.y < 0)
{
velocity.y = 0f;
}
float x = Input.GetAxis("Horizontal");
float z = Input.GetAxis("Vertical");
Vector3 move = transform.right * x + transform.forward * z;
controller.Move(move * speed * Time.deltaTime);
velocity.y += gravity * Time.deltaTime;
controller.Move(velocity * Time.deltaTime);
if(Input.GetKey(KeyCode.LeftShift))
{
speed = 24;
}
else
{
speed = 12;
}
if(Input.GetButtonDown("Jump") && isGrounded)
{
velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
}
}
}
【问题讨论】:
-
是否有任何对撞机标记为
IsTrigger?你有没有检查物理设置 -> 层碰撞矩阵?也许你的图层会互相忽略?
标签: unity3d