![](/img/trans.png)
[英]How do I rotate a GameObject with a RigidBody based on it's movement direction? Unity | 3D | C#
[英]How do I make a grid based movement in c# for unity
我觀看並嘗試在 c# 中重新創建 5 種不同類型的網格運動以實現統一,但沒有一個視頻可以正常工作或以可理解的方式對其進行解釋。 我的最后一次嘗試是使用這段代碼,但我沒有找到任何有用的信息供初學者使用......帶有碰撞檢測的基於網格的運動?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NewBehaviourScript : MonoBehaviour
{
private bool isMoving;
private Vector3 origPos, targetPos;
private float timeToMove = 0.2f;
void Update()
{
if(Input.GetKey(KeyCode.W) && !isMoving)
StartCoroutine/(MovePlayer(Vector3.up));
if(Input.GetKey(KeyCode.A) && !isMoving)
StartCoroutine/(MovePlayer(Vector3.up));
if(Input.GetKey(KeyCode.S) && !isMoving)
StartCoroutine/(MovePlayer(Vector3.up));
if(Input.GetKey(KeyCode.D) && !isMoving)
StartCoroutine/(MovePlayer(Vector3.up));
}
private IEnumerator MovePlayer(Vector3 direction)
{
isMoving = true;
float elapsedTime = 0;
origPos = transform.position;
targetPos = origPos + direction;
while(elapsedTime < timeToMove)
{
transform.position = Vector3.Lerp(origPos, targetPos, (elapsedTime / timeToMove));
elapsedTime += Time.deltaTime;
yield return null;
}
transform.position = targetPos;
isMoving = false;
}
}
在協程中,您可以使用 transform.position = new Vector3(); 將 object 移動到您想要的任何軸(根據按鍵); 之后,您可以使用 yield return new WaitForSeconds(0.25f) 設置 0.25 秒的延遲;
我希望我理解你的問題,謝謝!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.