- Home /
Temporarily disable blayer movement?
Hello,
In my game when the player hits a wall he shouldn't be able to move for about 5 seconds. I got it to be disabled, howeveri can't get it to go back to enabled. Here is my entire movement script:
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class movement : MonoBehaviour {
public Rigidbody2D player;
public float speed;
public float rotSpeed;
public GameObject wall;
public float delay;
private bool movementEnabled = true;
// Use this for initialization
void Start () {
player = GetComponent<Rigidbody2D>();
wall = GetComponent<GameObject>();
}
IEnumerator timeDisabled ()
{
yield return new WaitForSeconds(delay);
movementEnabled = true;
}
void OnCollisionEnter2D(Collision2D wall)
{
movementEnabled = false;
}
void RotateLeft()
{
transform.Rotate(Vector3.forward * rotSpeed);
}
void RotateRight()
{
transform.Rotate(Vector3.back * rotSpeed);
}
void move()
{
if (Input.GetKey(KeyCode.W))
{
player.velocity = (transform.up * speed);
}
else
{
player.velocity = new Vector2(0, 0);
}
if (Input.GetKey(KeyCode.A))
{
RotateLeft();
}
if (Input.GetKey(KeyCode.D))
{
RotateRight();
}
}
// Update is called once per frame
void Update () {
if (movementEnabled == true)
{
move();
}
else
{
timeDisabled();
}
}
}
If you can help i'll gladly try anithing.
Thank you.
Answer by OneCept-Games · Jan 02, 2018 at 02:57 PM
Sure OnCollisionEnter2D() is called? Call timeDisabled() as a Coroutine (StartCoroutine(timeDisabled);)
I am sure that OnCollisionEnter2D() is called. Not so much about (timeDisabled). $$anonymous$$y player cannot move once they collide, but it stays like that.
Put a Debug.Log() in your OnCollisionEnter2D() function to see if it is called. But i think it is, because you say that you get stuck, and movementDisabled is never set back to false.
Wrap StartCoroutine() around your call to timeDisabled, else it will never pass the yield command.
How should i format it? StartCoroutine(timeDisabled); ? I haven't really used this, so i'm not sure/
Your answer
Follow this Question
Related Questions
How to delay a function (how to use WaitForSeconds() and yield) 1 Answer
Boost Script Time problems 1 Answer
Waitforseconds vs Time 2 Answers
Yielding for a changing amount of time? 2 Answers