如果这是一个非常基本的问题,我深表歉意;我是团结的新手,只是在学习。我正在尝试制作一款统一的小游戏,但遇到涉及移动平台的代码问题。当玩家在平台上时,平台在移动,我想让玩家跟着移动。但是,我似乎无法让它工作。我的播放器移动代码如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
public class PlayerMovement : MonoBehaviour
{
[SerializeField]
private float walkSpeed = 4.0f;
[SerializeField]
private float jumpHeight = 2.0f;
[SerializeField]
private float gravity = -9.81f;
[SerializeField]
private float rotationSpeed = 5.0f;
private CharacterController characterController;
private PlayerInput playerInput;
private Transform cameraTransform;
private InputAction moveAction;
private InputAction jumpAction;
private Vector3 playerVelocity;
private bool isGrounded;
private void Awake()
{
characterController = GetComponent<CharacterController>();
playerInput = GetComponent<PlayerInput>();
cameraTransform = Camera.main.transform;
moveAction = playerInput.actions["Walk"];
jumpAction = playerInput.actions["Jump"];
Cursor.lockState = CursorLockMode.Locked;
}
private void Update()
{
isGrounded = characterController.isGrounded;
if (isGrounded && playerVelocity.y < 0)
{
playerVelocity.y = -5.0f;
gravity = -9.81f;
}
Vector2 input = moveAction.ReadValue<Vector2>();
Vector3 move = new Vector3(input.x, 0f, input.y);
Vector3 cameraForwardDirection = new Vector3(Camera.main.transform.forward.x, 0, Camera.main.transform.forward.z);
Vector3 cameraRightDirection = new Vector3(Camera.main.transform.right.x, 0, Camera.main.transform.right.z);
move = cameraForwardDirection * move.z + cameraRightDirection * move.x;
characterController.Move(move * Time.deltaTime * walkSpeed);
if (jumpAction.triggered && isGrounded)
{
playerVelocity.y += Mathf.Sqrt(jumpHeight * -3.0f * gravity);
}
playerVelocity.y += gravity * Time.deltaTime;
characterController.Move(playerVelocity * Time.deltaTime);
float targetAngle = cameraTransform.eulerAngles.y;
Quaternion targetRotation = Quaternion.Euler(0, targetAngle, 0);
transform.rotation = Quaternion.Lerp(transform.rotation, targetRotation, rotationSpeed * Time.deltaTime);
}
public void PlatformMovement(Vector3 platformVelocity)
{
characterController.Move(platformVelocity);
}
}
我用来在平台上移动播放器的代码如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlatformStick : MonoBehaviour
{
private void OnTriggerStay(Collider other)
{
if (other.gameObject.CompareTag("Player"))
{
PlayerMovement playerMovement = other.gameObject.GetComponent<PlayerMovement>();
Rigidbody rigidbody = GetComponent<Rigidbody>();
playerMovement.PlatformMovement(rigidbody.velocity);
}
}
}
我尝试使用 Debug.Log() 来查看是否正在调用 PlatformMovement() 方法,似乎是,它只是运动不起作用。