【发布时间】:2021-06-10 23:47:17
【问题描述】:
我有一个带有相机的胶囊对象。胶囊具有带网格的胶囊对撞机、角色控制器。圆柱体对象(硬币)是盒子对撞机,触发选项处于打开状态。 OnTriggerObject 方法无助于破坏硬币对象。即使使用了 OnCollisionEnter,最终也有同样的结果。还尝试将刚体添加到玩家对象并从硬币对象中删除。甚至不记得我试过什么。 这是附加到胶囊对象的脚本:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
// Start is called before the first frame update
[SerializeField] Transform playerCamera = null;
[SerializeField] float mouseSensitivity = 3.5f;
[SerializeField] float walkSpeed = 6.0f;
[SerializeField] float gravity = -13.0f;
[SerializeField] [Range(0.0f, 0.5f)] float moveSmoothTime = 0.3f;
[SerializeField] [Range(0.0f, 0.5f)] float mouseSmoothTime = 0.03f;
[SerializeField] bool lockCursor = true;
float cameraPitch = 0.0f;
float velocityY = 0.0f;
CharacterController controller = null;
Vector2 currentDir = Vector2.zero;
Vector2 currentDirVelocity = Vector2.zero;
Vector2 currentMouseDelta = Vector2.zero;
Vector2 currentMouseDeltaVelocity = Vector2.zero;
void Start()
{
controller = GetComponent<CharacterController>();
if (lockCursor)
{
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
}
}
// Update is called once per frame
void Update()
{
UpdateMouseLook();
UpdateMovement();
}
void UpdateMouseLook()
{
Vector2 targetMouseDelta = new Vector2(Input.GetAxis("Mouse X"), Input.GetAxis("Mouse Y"));
currentMouseDelta = Vector2.SmoothDamp(currentMouseDelta, targetMouseDelta, ref currentMouseDeltaVelocity, mouseSmoothTime);
cameraPitch -= currentMouseDelta.y * mouseSensitivity;
cameraPitch = Mathf.Clamp(cameraPitch, -90.0f, 90.0f);
playerCamera.localEulerAngles = Vector3.right * cameraPitch;
transform.Rotate(Vector3.up * currentMouseDelta.x * mouseSensitivity);
}
void UpdateMovement()
{
Vector2 targetDir = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
targetDir.Normalize();
currentDir = Vector2.SmoothDamp(currentDir, targetDir, ref currentDirVelocity, moveSmoothTime);
if (controller.isGrounded)
velocityY = 0.0f;
velocityY += gravity * Time.deltaTime;
Vector3 velocity = (transform.forward * currentDir.y + transform.right * currentDir.x) * walkSpeed + Vector3.up * velocityY;
controller.Move(velocity * Time.deltaTime);
}
private void OnCollisionEnter(Collision other)
{
if(other.gameObject.tag == "coins")
{
Destroy(other.gameObject);
}
}
}
【问题讨论】:
-
void OnControllerColliderHit(ControllerColliderHit other) 也不起作用(
-
它的标签是否设置为硬币?您应该为此使用触发器输入。也尝试使用触发停留。
-
@ken,是的,硬币有标签“硬币”,并且设置了触发
-
我的意思是你应该使用 OnTriggerEnter 而不是 OnCollisionEnter。在 OnTriggerEnter 中输出一条打印语句,看看它是否被调用。
-
请使用正确的标签!请注意,
unityscript是或更好地曾经是一种 JavaScript 风格,类似于早期 Unity 版本中使用的自定义语言,并且现在已经不推荐使用了!你的代码显然是c#