我有一个相对于相机的动作。像超级马里奥64等。首先我用CharacterController制作但我想要进行默认的碰撞检测,所以我需要使用与刚体的对撞机。
我的代码看起来像这样:
public class PlayerMovementController : PlayerCommonController
{
PlayerMovementData data; // data class
PlayerMovementView view; // animation, etc. ... class
float turnSmoothVelocity;
float speedSmoothVelocity;
private void Start()
{
data = new PlayerMovementData();
view = new PlayerMovementView();
}
private void Update()
{
Vector2 inputDirection = (new Vector2(data.InputHorizontal, data.InputVertical)).normalized; // get the inputs
if (Input.GetButtonDown("Jump"))
{
if (data.PlayerCharacterController.isGrounded) // player is on ground?
data.VelocityY = Mathf.Sqrt(-2 * data.PlayerGravity * data.JumpPower);
}
if (inputDirection != Vector2.zero) // Rotate the player
{
transform.eulerAngles = Vector3.up * Mathf.SmoothDampAngle(
transform.eulerAngles.y,
Mathf.Atan2(inputDirection.x, inputDirection.y) * Mathf.Rad2Deg + data.CameraTransform.eulerAngles.y,
ref turnSmoothVelocity,
GetModifiedSmoothTime(data.TurnSmoothTime));
}
data.CurrentMovementSpeed = Mathf.SmoothDamp( /* Set the movementspeed */
data.CurrentMovementSpeed,
data.MovementSpeed * inputDirection.magnitude,
ref speedSmoothVelocity,
GetModifiedSmoothTime(data.SpeedSmoothTime));
data.VelocityY += data.PlayerGravity * Time.deltaTime; // vertical velocity
Vector3 velocity = transform.forward * data.CurrentMovementSpeed + Vector3.up * data.VelocityY; // set the players velocity
data.PlayerCharacterController.Move(velocity * Time.deltaTime); // Move the player
data.CurrentMovementSpeed = (new Vector2(data.PlayerCharacterController.velocity.x, data.PlayerCharacterController.velocity.z)).magnitude; // Calc movementspeed
if (data.PlayerCharacterController.isGrounded) // Set the vertical vel. to 0 when grounded
data.VelocityY = 0;
}
float GetModifiedSmoothTime(float smoothTime) // Handle the movement while in air
{
if (data.PlayerCharacterController.isGrounded)
return smoothTime;
if (data.AirControlPercentage == 0)
return float.MaxValue;
return smoothTime / data.AirControlPercentage;
}
}
因此用Rigidbody关键字替换所有CharacterController变量似乎很明显。但是谈到
data.PlayerCharacterController.Move(velocity * Time.deltaTime);
我不知道该替换什么。当我没有CC但是一个Collider和一个Rigidbody我从地面掉下来。这可能是因为代码而发生的。
有人可以帮助我吗?
答案 0 :(得分:1)
从播放器中移除CharacterController
组件并附加Rigidbody
组件。然后使用
GetComponent<Rigidbody>().velocity = velocity * Time.deltaTime;
我建议您创建一个附加刚体的参考,并使用它而不是GetComponent
。