I’m making a character move on top of tiles based on a raycasthit2d that is supposed to assess each tile for various checks before actually moving the player. The problem is that I can’t quite grasp the concept of Raycasthit2D for some reason (and I’m kind of dodgy when it comes to calling other scripts). Here’s a bit of code that isn’t functional at all, and I just can’t seem to find out where things are going wrong:
UPDATED CODE
STILL NOT FUNCTIONAL
using UnityEngine;
using System.Collections;
public class Player1 : MonoBehaviour {
public int playerID = 1;
public int pHP = 1000;
public float spotX = -4.2f;
public float spotY = -0.25f;
public LayerMask NotToHit;
Transform rightPoint;
// Use this for initialization
void Awake ()
{
rightPoint = transform.FindChild("RightPoint");
}
void Start () {
}
// Update is called once per frame
void Update () {
//Vector3 spot = new Vector3( spotX, spotY, 0);
// Vector3 origin = new Vector3 (this.transform.position.x, this.transform.position.y, 0);
// origin = new Vector2(this.transform.position.x, this.transform.position.y);
Vector2 rightFacing = new Vector2 (rightPoint.position.x, rightPoint.position.y);
if(Input.GetKeyDown(KeyCode.RightArrow))
{
RaycastHit2D moveCheck = Physics2D.Raycast (rightFacing, Vector2.right, 2.9f, NotToHit);
if (moveCheck.collider != null)
{
Debug.DrawRay(transform.position, Vector3.right, Color.cyan);
Debug.Log(moveCheck.collider.name);
Tile tileInfo = GetComponent<Tile>();
Debug.Log ("Got tile comp");
bool canMove = tileInfo.moveable;
if(tileInfo.moveable == true)
{
Debug.Log("TRUUUUUUUUUU");
spotX = spotX + 1.25f;
transform.position = new Vector3(spotX, spotY, 0);
}
}
}
The raycasthit is supposed to assess each tile to ensure that a bool variable named “moveable” is true, but it just let’s me go anywhere. I can even move off of the grid entirely. I really just need to know what’s preventing this from working. Pardon the weak coding, I’m still adjusting to Unity.
UPDATE: I since created a new empty GameObject called “RightPoint” placed at the right-most corner in my Player collider with NotToHit LayerMask set to not detect the Player layer. The Player object IS in fact in the Player layer, yet moveCheck.collider.name is still returning “Player” on the console. Why is this happening?? I have no clue why it isn’t detecting the tiles instead.