c# - 每当我的角色转身时,运动脚本就不会前进
问题描述
我将这个移动脚本附加到我的播放器上,但是每当我转动例如 90 度时,如果我按下 w,它就不会前进,现在我知道这是因为 z 不同,因为我移动了相机但是我该如何解决这个问题?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(Rigidbody))]
public class PlayerMovement : MonoBehaviour
{
public Rigidbody rb;
float forwardForce = 500f;
float sidewaysForce = 500f;
float jumpForce = 100f;
// Start is called before the first frame update
// Update is called once per frame
public Vector3 jump;
public bool isGrounded;
void Start()
{
rb = GetComponent<Rigidbody>();
}
void OnCollisionStay()
{
isGrounded = true;
}
void FixedUpdate()
{
if (Input.GetKey("d"))
{
rb.AddForce(sidewaysForce * Time.deltaTime, 0, 0);
}
if (Input.GetKey("a"))
{
rb.AddForce(-sidewaysForce * Time.deltaTime, 0, 0);
}
if (Input.GetKey("w"))
{
rb.AddForce(0, 0, forwardForce * Time.deltaTime);
}
if (Input.GetKey("s"))
{
rb.AddForce(0, 0, -forwardForce * Time.deltaTime);
}
if (Input.GetKey("space") && isGrounded)
{
rb.AddForce(0, jumpForce, 0);
isGrounded = false;
}
}
}
解决方案
AddForce
使用世界空间。因此,无论您的对象如何旋转,它都将始终沿 Unity 全局 X、Y、Z 轴施加力。
您想使用AddForceRelative
which 解释该对象的局部空间中的给定值(因此使用其自己的 X、Y、Z 轴)
相对于其坐标系向刚体添加力。
void FixedUpdate()
{
if (Input.GetKey("d"))
{
rb.AddForceRelative(sidewaysForce * Time.deltaTime, 0, 0);
}
if (Input.GetKey("a"))
{
rb.AddForceRelative(-sidewaysForce * Time.deltaTime, 0, 0);
}
if (Input.GetKey("w"))
{
rb.AddForceRelative(0, 0, forwardForce * Time.deltaTime);
}
if (Input.GetKey("s"))
{
rb.AddForceRelative(0, 0, -forwardForce * Time.deltaTime);
}
if (Input.GetKey("space") && isGrounded)
{
// Here you most probably would want to keep the global UP direction ;)
rb.AddForce(0, jumpForce, 0);
isGrounded = false;
}
}
通常,您可能希望使用与相机不同的对象进行移动。
为什么?
因为否则
- 如果你的相机向下看并且你按下 W -> 你向下添加一个力,这样试图将玩家压入地面
- 如果您的相机向上看并且您按 W -> 您会向上添加一个力,因此根据您的力的强度,这可能会使玩家四处飞行^^
所以我宁愿使用像这样的层次结构
Player (This one receives the movement WASD + ONLY global Y-axis rotation)
|--Camera (This one receives ONLY local X-axis rotation)
当然,您可以在一个脚本中处理这两种情况,但您应该在其中应用给定的输入。这样,它Player
实际上永远不会向下或向上看,因为它只会围绕全局 Y 轴旋转(向左和向右看)。
相机是唯一向下和向上看的东西,但我们不使用它的局部空间进行运动,而是使用其中之一,Player
因此相机方向对运动无关紧要。
推荐阅读
- java - 如何使用 JPA 管理多个实体?
- sql - 为什么将工作查询限制为 WHERE ROWNUM <=10 会导致 EXPLAIN PLAN “ORA-12899: value too large for column”出错?
- javascript - Chrome 扩展:在 URL 更新时调用后台
- c# - 带有 MySQL 的 Windows 窗体 C# 实体框架 6
- java - 找不到 GlideApp
- android - React Native 0.57.7 - Android 构建在任务中失败:app:mergeReleaseResources
- javascript - 在 ReactJS 中,使用 Reactstrap,我希望我的警报保持在它开始的屏幕上的同一个位置
- java - 定制肥皂响应
- symfony - Symfony 4.2.3 - 用户注册电子邮件域时设置 ManyToOne Id
- spring-boot - 如何以编程方式获得 Start-Class?