[英]How do I make a grid based movement in c# for unity
I watched and tried to recreate 5 different types of grid movement for unity in c# and yet there was not a single video that worked or had it explained in an understandable way.我观看并尝试在 c# 中重新创建 5 种不同类型的网格运动以实现统一,但没有一个视频可以正常工作或以可理解的方式对其进行解释。 My last try was with this code and I just don't find any useful information for a beginner to work with... Are there good sites to learn how to recreate a Pokémon game in unity that actually works, and how do I make a grid-based movement with collision detection?
我的最后一次尝试是使用这段代码,但我没有找到任何有用的信息供初学者使用......带有碰撞检测的基于网格的运动?
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;
}
}
In the coroutine you can move the object by whatever axis you want (according to the key press) by using transform.position = new Vector3();在协程中,您可以使用 transform.position = new Vector3(); 将 object 移动到您想要的任何轴(根据按键); after that you can set a delay of 0.25 seconds by using yield return new WaitForSeconds(0.25f);
之后,您可以使用 yield return new WaitForSeconds(0.25f) 设置 0.25 秒的延迟;
I hope I understood your question, Thanks!我希望我理解你的问题,谢谢!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.