Hello. I’m new to Unity and C# and have started work on a little project as a way to learn some things. So far I’ve been having a great time writing some basic C# after going through the official scripting tutorials, but I have ran into something that I am having trouble implimenting.
My project is a top-down grid-based game where if you move up (by pressing W), the character jumps up one space. This is achived by using transform.Translate followed by the direction. At the moment, everything in the scene is a 1x1x1 cube, and so the character moves by 1 block with every button press.
I’ve also added collision detection using raycasts to detect if a wall is nearby and stopping the movement script from being activated when nearby. Here is my code so far:
using UnityEngine;
using System.Collections;
public class CharacterMovement : MonoBehaviour
{
void Update ()
{
// Move up
{
RaycastHit hit;
if (Physics.Raycast(transform.position, Vector3.forward, out hit, 1.0F)) {}
else if (Input.GetKeyDown(KeyCode.W))
transform.Translate(0, 0, 1f);
}
// Move down
{
RaycastHit hit;
if (Physics.Raycast(transform.position, -Vector3.forward, out hit, 1.0F)) {}
else if (Input.GetKeyDown(KeyCode.S))
transform.Translate(0, 0, -1f);
}
// Move left
{
RaycastHit hit;
if (Physics.Raycast(transform.position, -Vector3.right, out hit, 1.0F)) {}
else if (Input.GetKeyDown(KeyCode.A))
transform.Translate(-1f, 0, 0);
}
// Move right
{
RaycastHit hit;
if (Physics.Raycast(transform.position, Vector3.right, out hit, 1.0F)) {}
else if (Input.GetKeyDown(KeyCode.D))
transform.Translate(1f, 0, 0);
}
}
}
So that’s what I’ve got right now. What I want to achieve is a smooth but quick transition between spaces on the grid. At the moment the character will simply snap in the direction they want to go. I’ve tried to add Lerp to the transform but from my understanding it only really seems to work between two pre-written vector3 points while I need to be able to move by 1 square infinitely in either direction.
I’d greatly appreciate it if anyone could give me a hand here.