[Unity 2D]Grid Based Character Movement Issues with Vector3D.movetowards
So I am new to C# and Unity...I am trying to create a script that allows the object to move in a grid-fashion (fixed unit displacement of the object per direction input). My current code represents a free movement style...
So here is the code:
using UnityEngine;
using System.Collections;
public class PlayerMovement : MonoBehaviour
{
public LayerMask BlockingLayer;
private BoxCollider2D Box_Collider;
private Rigidbody2D RB2D;
RaycastHit2D hit;
Vector3 pos; // For movement
float speed = 2.0f; // Speed of movement
void Start()
{
Box_Collider = GetComponent<BoxCollider2D>();
RB2D = GetComponent<Rigidbody2D>();
pos = transform.position; // Take the initial position
print(pos);
}
void FixedUpdate()
{
DirectionCheck(pos);
pos = transform.position;
}
void DirectionCheck(Vector3 pos)
{
if (Input.GetKey(KeyCode.LeftArrow) && transform.position == pos)
{
pos += Vector3.left; // Left
print(pos);
CanMove(pos,out hit);
return ;
}
if (Input.GetKey(KeyCode.RightArrow) && transform.position == pos)
{
pos += Vector3.right; // Right
print(pos);
CanMove(pos, out hit);
return ;
}
if (Input.GetKey(KeyCode.UpArrow) && transform.position == pos)
{
pos += Vector3.up; // Up
print(pos);
CanMove(pos, out hit);
return;
}
if (Input.GetKey(KeyCode.DownArrow) && transform.position == pos)
{
pos += Vector3.down; // Down
print(pos);
CanMove(pos, out hit);
return;
}
return;
}
bool CanMove(Vector3 pos,out RaycastHit2D hit) {
//print(pos);
Box_Collider.enabled = false;
hit = Physics2D.Linecast(transform.position, pos, BlockingLayer);
Box_Collider.enabled = true;
MovePlayer(pos,hit);
return hit;
}
private RaycastHit2D MovePlayer(Vector3 pos,RaycastHit2D hit)
{
if (!hit)
{
transform.position = Vector3.MoveTowards(RB2D.position, pos, Time.deltaTime * speed);// Move there
RB2D.MovePosition(transform.position);
// print(pos);
return hit;
}
else{
//print(pos);
return hit;
}
}
}
I use getkey() to get the input directions to move which is done by : "vector3.right/down/left/up"
I have used Physics2D.Linecast to detect collision at the destination and return true/false with "hit"... then Vector3.movetowards does the moving...but the code ended up not moving in grids....
any directions to how to implement a grid-based movement?
Your answer
Follow this Question
Related Questions
Movement Colliding Improperly In Two Directions 0 Answers
Cursor collision 0 Answers
No Gravity Jump 0 Answers
how to move a gameobject based on a dice roll 1 Answer
How do I count Hits ?? 2 Answers