Hello my fellow Unity friends I have an issue.
I’m using a basic blink (teleport) ability which just directly shifts the player’s transform. the problem is I have certain walls I don’t want the player to be able to teleport through. I’m trying to use the below script to prevent the player when they are at a 1.5 distance from the “Barriers”. This distance is the exact blink distance the player can move.
Edit: This function is called in a fixed update
If any more information is needed, I have more.
Thank you all in advance!
Edit (1/1/2018):
Code now gives the error:
NullReferenceException: Object reference not set to an instance of an object
Blink.BarrierCheck () (at Assets/Scripts/Hope/Abilities/Blink.cs:41)
Blink.FixedUpdate () (at Assets/Scripts/Hope/Abilities/Blink.cs:30)
public class Blink : MonoBehaviour
{
public bool CanBlink;
public bool Allowblink;
public Animator Anim;
public GameObject Player;
public Vector3 OldPos;
public Vector3 NewPos;
public float BlinkCooldown;
Movement movement;
public void Start()
{
CanBlink = true;
Allowblink = true;
Player = GameObject.FindGameObjectWithTag("Player");
movement = GetComponent<Movement>();
BlinkCooldown = 3.0f;
}
public void FixedUpdate()
{
BarrierCheck();
BlinkWatcher();
}
public void BarrierCheck()
{
if (GameObject.FindGameObjectWithTag("Player").GetComponent<Movement>().facingRight)
{
RaycastHit2D hit = (Physics2D.Raycast(transform.position, transform.right, 3f, (LayerMask.GetMask("Barrier"))));
Debug.DrawRay(transform.position, transform.right, Color.black);
if (hit.collider.CompareTag("Barrier"))
{
Allowblink = false;
Debug.Log("Collider was hit");
}
else
{
Debug.Log("Null ray");
}
}
else
{
RaycastHit2D hit = (Physics2D.Raycast(transform.position, -transform.right, 3f, (LayerMask.GetMask("Barrier"))));
Debug.DrawRay(transform.position, -transform.right, Color.black);
if (hit.collider.CompareTag("Barrier"))
{
Allowblink = false;
Debug.Log("Collider was hit");
}
else
{
Debug.Log("Null ray");
}
}
}
public void BlinkWatcher()
{
BlinkCooldown -= Time.deltaTime;
if (Input.GetKey(KeyCode.Mouse1) && CanBlink && Allowblink && BlinkCooldown <= 0f)
{
float x = movement.facingRight ? 3f : -3f;
Player.transform.position += new Vector3(x, 0f, 0f);
BlinkCooldown = 3.0f;
}
}
}