【发布时间】:2023-04-01 08:12:01
【问题描述】:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public GameObject player;
public Rigidbody2D playerRB;
public Transform playerTF;
public float moveForce;
public float rotateForce;
private string currentMoveKey = "";
private string currentRotateKey = "";
void Update()
{
//move
if(Input.GetKey("w") && currentMoveKey == "")
{
currentMoveKey = "w";
playerRB.AddForce(transform.up * moveForce * Time.deltaTime);
}
if (Input.GetKeyUp("w") && currentMoveKey == "w")
{
playerRB.velocity = new Vector2(0, 0);//resets when keyup and not already reset
currentMoveKey = "";
}
if (Input.GetKey("s") && currentMoveKey == "")
{
currentMoveKey = "s";
playerRB.AddForce(transform.up * -moveForce * Time.deltaTime);
}
if (Input.GetKeyUp("s") && currentMoveKey == "s")
{
playerRB.velocity = new Vector2(0, 0);
currentMoveKey = "";
}
//rotate
if (Input.GetKeyDown("a") && currentRotateKey == "")
{
currentRotateKey = "a";
}
if (Input.GetKey("a") && currentRotateKey == "a")
{
playerTF.Rotate(transform.forward * rotateForce * Time.deltaTime);
}
if (Input.GetKeyUp("a") && currentRotateKey == "a")
{
currentRotateKey = "";
}
if (Input.GetKeyDown("d") && currentRotateKey == "")
{
currentRotateKey = "d";
}
if (Input.GetKey("d") && currentRotateKey == "d")
{
playerTF.Rotate(transform.forward * -rotateForce * Time.deltaTime);
}
if (Input.GetKeyUp("d") && currentRotateKey == "d")
{
currentRotateKey = "";
}
}
}
你好!出于某种原因,在我将强制添加到 RigidBody2D 的行中,如果我在玩家移动的同时旋转玩家 - 从而改变 transform.up 指向的位置 - 玩家继续朝他最初指向的方向移动.换句话说,他看起来像是在滑动,我必须停止移动并再次开始移动以更新他指向的方向。我可以做些什么来解决这个问题,以便当他旋转时,他移动的方向会同时更新?
【问题讨论】:
-
RigidBody.AddForce在世界坐标中添加一个力,而不是本地坐标。请改用RigidBody.AddRelativeForce。