I have this little game, where my player is moving around a simple level, using a grid based movement script (See code below). My problem is that I have tried to implement a 2D raycast, which has to detect if the next 'tile' is a movable tile (not a wall). However all the examples I have found on the internet hasn't been something I could make work. So please help me with how I can detect if the player is allowed to move, before he moves.
I am using Unity 5.
using System.Collections;
using UnityEngine;
public class GridMove : MonoBehaviour {
public float moveSpeed = 2f;
private float gridSize = 1f;
private enum Orientation {
Horizontal,
Vertical
};
private Orientation gridOrientation = Orientation.Vertical;
private bool allowDiagonals = false;
private bool correctDiagonalSpeed = true;
private Vector2 input;
private bool isMoving = false;
private Vector3 startPosition;
private Vector3 endPosition;
private float t;
private float factor;
private Animator animator;
// Use this for initialization
void Start () {
animator = GetComponent<Animator>();
}
public void Update() {
if (!isMoving) {
input = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
if (!allowDiagonals) {
if (Mathf.Abs(input.x) > Mathf.Abs(input.y)) {
input.y = 0;
} else {
input.x = 0;
}
}
if (input != Vector2.zero) {
StartCoroutine(Move(transform));
animator.SetBool("isWalking", true);
}
else {
animator.SetBool("isWalking", false);
}
}
}
public IEnumerator Move(Transform transform) {
isMoving = true;
startPosition = transform.position;
t = 0;
animator.SetFloat("x", input.x);
animator.SetFloat("y", input.y);
if(gridOrientation == Orientation.Horizontal) {
endPosition = new Vector3(startPosition.x + System.Math.Sign(input.x) * gridSize,
startPosition.y, startPosition.z + System.Math.Sign(input.y) * gridSize);
} else {
endPosition = new Vector3(startPosition.x + System.Math.Sign(input.x) * gridSize,
startPosition.y + System.Math.Sign(input.y) * gridSize, startPosition.z);
}
if(allowDiagonals && correctDiagonalSpeed && input.x != 0 && input.y != 0) {
factor = 0.7071f;
} else {
factor = 1f;
}
while (t < 1f) {
t += Time.deltaTime * (moveSpeed/gridSize) * factor;
transform.position = Vector3.Lerp(startPosition, endPosition, t);
yield return null;
}
isMoving = false;
yield return 0;
}
}