Hey guys! I need a bit of help with this script for my sidescroller. I want to have the player stop moving when the space bar is held down, and, when released, have him resume movement unhindered. I’ve had some issues implementing this code, was hoping for some help.
void FixedUpdate ()
{
float moveHorizontal = Input.GetAxis ("Horizontal");
float moveVertical = Input.GetAxis ("Vertical");
Vector3 movement = new Vector3 (moveHorizontal, moveVertical, 0.0f);
rigidbody.velocity = movement * speed;
rigidbody.position = new Vector3
(
Mathf.Clamp (rigidbody.position.x, boundary.xMin, boundary.xMax),
Mathf.Clamp (rigidbody.position.y, boundary.yMin, boundary.yMax),
0.0f
);
if (Input.GetButtonDown("SpaceBar"))
{
rigidbody.constraints = RigidbodyConstraints.FreezePositionX | RigidbodyConstraints.FreezePositionY;
}
if (Input.GetButtonUp("SpaceBar"))
{
rigidbody.constraints = RigidbodyConstraints.None;
}
Here is the rigidbody.constraint attempt I tried first. It only works half the time, with the game occasionally not releasing the constraint. This results in the player pressing the space bar multiple times before the constraint will be lifted. The opposite is true also: sometimes the spacebar being pressed down sometimes doesn’t work.
void FixedUpdate ()
{
float moveHorizontal = Input.GetAxis ("Horizontal");
float moveVertical = Input.GetAxis ("Vertical");
Vector3 movement = new Vector3 (moveHorizontal, moveVertical, 0.0f);
rigidbody.velocity = movement * speed;
rigidbody.position = new Vector3
(
Mathf.Clamp (rigidbody.position.x, boundary.xMin, boundary.xMax),
Mathf.Clamp (rigidbody.position.y, boundary.yMin, boundary.yMax),
0.0f
);
if (Input.GetButton("SpaceBar"))
{
rigidbody.position = new Vector3
(
Mathf.Clamp (rigidbody.position.x, 0.0f, 0.0f),
Mathf.Clamp (rigidbody.position.y, 0.0f, 0.0f),
Mathf.Clamp (rigidbody.position.z, 0.0f, 0.0f)
);
}
Here is another attempt at it with clamps. This code hardly even works! It teleports the player into the middle of the game screen, and only marginally inhibits movement. By that I mean the player can still move only a little.
If anybody could help me out that’d be awesome! Thanks for taking the time to read this thread. If you wish for the entire script you can download it here.
1892067–121812–PlayerController.cs (991 Bytes)