- Home /
Question by
Campingmayor · Apr 02, 2015 at 12:28 PM ·
movementbuttonstuck
Button input getting stuck
So I use Buttons to control my player from the left to the right. When he collides with a Spike the character dies and the input gets deactivated until he respawns after 2 seconds. My problem is now that after the respawn the player character keeps the speed he had when colliding with the spike.
using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;
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()
{
if (PlayerDead == false) {
// 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;
}
}
}
Comment