Hello there
I have my Player move with buttons from the canvas. I press the Button and walk into a Spike which kills the player.
Now I added a wait of 2 seconds before respawning in which the bool PlayerDead is set to true so you cant move and after the 2 Seconds and the respawn I set it back to false.
Now my problem is that after respawning the player keeps the speed that was pressed before the death. How can I fix this?
Thanks for the answers.
using UnityEngine;
using System.Collections;
public class PlayerMovement : MonoBehaviour {
// speed
public float speed = 30;
float hInput = 0;
Transform myTrans;
Rigidbody2D myBody;
// save the checkpoint
Transform check;
// check if the player is not dead
public bool PlayerDead = false;
void Start()
{
myBody = this.GetComponent<Rigidbody2D>();
myTrans = this.transform;
}
void OnTriggerEnter2D(Collider2D co)
{
// checkpoint?
if (co.gameObject.tag == "Checkpoint")
check = co.transform;
}
// Update is called once per frame
void Update () {
// Horizontal Movement
//float h = Input.GetAxisRaw ("Horizontal");
//GetComponent<Rigidbody2D> ().velocity = Vector2.right * h * speed;
// Gravity Changes
if (Input.GetKeyDown (KeyCode.Space)) {
GetComponent<Rigidbody2D> ().gravityScale *= -1;
transform.Rotate (0, 180, 180);
}
}
void Move(float horizontalInput)
{
// the move command which is applied to the player
// 1. new vector
// 2. what the vector is
// 3. apply to the players body
Vector2 moveVel = myBody.velocity;
moveVel.x = horizontalInput * speed;
myBody.velocity = moveVel;
}
void FixedUpdate()
{
// just calling the player to move every physics update
Move (hInput);
}
public void StartMoving(float horizontalInput)
{
if (PlayerDead == false) {
// the command for the button to move
hInput = horizontalInput;
}
}
public void ButtonGravity()
{
if (PlayerDead == false)
{
GetComponent<Rigidbody2D> ().gravityScale *= -1;
transform.Rotate (0, 180, 180);
}
}
IEnumerator OnCollisionEnter2D(Collision2D co) {
// Collided with a Collidethingy?
if (co.gameObject.tag == "Spike") {
// Reset Rotation, Gravity, Velocity and go to last Checkpoint
PlayerDead = true;
yield return new WaitForSeconds(2);
transform.rotation = Quaternion.identity;
GetComponent<Rigidbody2D>().gravityScale = Mathf.Abs(GetComponent<Rigidbody2D>().gravityScale);
GetComponent<Rigidbody2D>().velocity = Vector2.zero;
transform.position = check.position;
PlayerDead = false;
}
}
}