Unity c#基于旋转的运动?



我目前正在使用Unity 3D中的网格,并且很难将我的玩家保持在网格上。我的移动脚本是这样工作的:

  1. 当'w'被按下时,rb。位置+= rb。旋转* Vector3。forward * 10;
  2. posX = rb.position.x/10, posY = rb.position.z/10

我目前的问题是我还没有找到如何让我的球员离开董事会的解决方案。这是非常困难的,因为基于玩家的旋转,"w"可以将+/- 1添加到x,或将+/- 1添加到y,这对于向左,向右和向后移动也是一样的,所有数值都基于旋转。

我还计划重做移动系统,以自动将玩家捕捉到变量posX和posY的值。我能想到的编程系统的唯一方法就是简单地硬编码(if (rotation = 0) {posX + 1}, if (rotation = 90) {posY + 1}, if (rotation = 180) {posX- 1}, if (rotation = 270) {posY - 1})。效率很低。

关于如何解决这个问题有什么想法吗?

public class Movement : MonoBehaviour
{   bool Rotating = false;
bool Moving = false;
public Rigidbody rb;
private Quaternion endRotation;
[SerializeField] private AnimationCurve curve;
private Quaternion startRotation;
private Vector3 startPosition;
public GameObject Grid;
private Vector3 endPosition;
public int xRange;
public int yRange;
public float posX;
public float posY;
public float desiredDuration = 1f;
private float elapsedTime;
float percentageComplete = 0f;  
private void Awake(){
rb = GetComponent<Rigidbody>();
var grid = Grid.GetComponent<GridCreation>();
xRange = grid.width;
yRange = grid.height;
}
public void TurnRight(InputAction.CallbackContext context){ 

if (context.started && Rotating == false && Moving == false) {
percentageComplete = 0;
startRotation = rb.rotation;
endRotation = startRotation * Quaternion.Euler(0,90,0);
Rotating = true;
elapsedTime = 0;
}
}
public void TurnLeft(InputAction.CallbackContext context){ 

if (context.started && Rotating == false && Moving == false) {
percentageComplete = 0;
startRotation = rb.rotation;
endRotation = startRotation * Quaternion.Euler(0,-90,0);
Rotating = true;
elapsedTime = 0;
}}
//MOVING BASED ON ROTATION//
public void Forward(InputAction.CallbackContext context){ 

if (context.started && Rotating == false && Moving == false) {
percentageComplete = 0;
startPosition = rb.position;
endPosition += rb.rotation * Vector3.forward * 10;
endPosition[1] = 1;
Moving = true;
elapsedTime = 0;
;
}}

public void Update() { 
if (Rotating == true){
if (percentageComplete < 1) {
elapsedTime += Time.deltaTime;
percentageComplete = elapsedTime / desiredDuration;
rb.rotation = Quaternion.Lerp(startRotation, endRotation, curve.Evaluate(percentageComplete));
}

if (percentageComplete > 1) {
Rotating = false;}
}
if (Moving == true){
if (percentageComplete < 1) {
elapsedTime += Time.deltaTime;
percentageComplete = elapsedTime / desiredDuration;
rb.position = Vector3.Lerp(startPosition, endPosition, curve.Evaluate(percentageComplete));
if (percentageComplete > 1) {
Moving = false;
// returns players current position on board
posX = Mathf.Round(rb.position.x / 10);
posY = Mathf.Round(rb.position.z / 10);}
}
}
}}

嘿,我认为你可以使用Colliders来防止玩家从板上掉下来!只要在棋盘周围添加Empty GameObjects并提供Collider,当玩家撞到Collider时,它就像一堵无形的墙,阻止玩家继续前进。你甚至可以在Collider中添加Material,让玩家在看不见的墙上反弹。我认为使用BoxCollider是最好的,因为它可能最适合你的网格。我希望我能帮到你!:)

最新更新