How do I make a grid based movement in c# for unity

Viewed 83

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. 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;
    }
}
1 Answers

In the coroutine you can move the object by whatever axis you want (according to the key press) by using transform.position = new Vector3(); after that you can set a delay of 0.25 seconds by using yield return new WaitForSeconds(0.25f);

I hope I understood your question, Thanks!

Related