How to add collision to Player controller?

Hello! Very new to coding and I have been following a couple tutorials.
I found a guide on how to do TileBased movement
My only problem is figuring out how to get this to interact with colliders, or getting the player to stop moving off the level.
Just need to get pointed in the right direction for this stuff.
Trying to recreate the old school zelda or pokemon movement.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Player : MonoBehaviour
{

    [SerializeField] private float distanceToMove;
    [SerializeField] private float moveSpeed;
    private bool moveToPoint = false;
    private Vector3 endPosition;

    void Start()
    {

        endPosition = transform.position;
    }

    void FixedUpdate()
    {
        if (moveToPoint)
        {
            transform.position = Vector3.MoveTowards(transform.position, endPosition, moveSpeed * Time.deltaTime);
        }
    }
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.A)) //Left
        {
            endPosition = new Vector3(endPosition.x - distanceToMove, endPosition.y, endPosition.z);
            moveToPoint = true;
        }
        if (Input.GetKeyDown(KeyCode.D)) //Right
        {
            endPosition = new Vector3(endPosition.x + distanceToMove, endPosition.y, endPosition.z);
            moveToPoint = true;
        }
        if (Input.GetKeyDown(KeyCode.W)) //Up
        {
            endPosition = new Vector3(endPosition.x, endPosition.y + distanceToMove, endPosition.z);
            moveToPoint = true;
        }
        if (Input.GetKeyDown(KeyCode.S)) //Down
        {
            endPosition = new Vector3(endPosition.x, endPosition.y - distanceToMove, endPosition.z);
            moveToPoint = true;
        }
    }
}

generally speaking you want to move your character with a character controller component, or a rigidbody + capsule collider method, or roll your own version of either which i wouldn’t recommend for starting out. in general, if you do google search for the character controller component and a simple implementation of it using it, then it should get you started down the soon to be rabbit hole of hell that a character motor can turn into depending on how complex or simple you wish it to be. good luck!

1 Like