I am at 1.2 stage (moving the player) at Unity course "Roll-a-ball" and have question:
I want to add feature that stops a player and sets his new position on 0, 0, 0.
I can reset the position, but I have really problem with stopping a player. The ball won't stop rolling.
My code is:
using UnityEngine;
using System.Collections;
public class PlayerController : MonoBehaviour {
private Rigidbody rb;
public float speed = 1.0f;
void Start()
{
rb = GetComponent<Rigidbody>();
}
void FixedUpdate()
{
float moveHorizontal = Input.GetAxis("Horizontal");
float moveVertical = Input.GetAxis("Vertical");
Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);
rb.AddForce(movement*speed);
if (Input.GetKeyDown(KeyCode.Space))
{
rb.position = new Vector3(0,0.5f,0);
}
print(movement);
}
}
What I tried?
- Adding new vector3 (0,0,0) in
if
section, - New vector3 that is opposite to movement,
.Stop
after ascribing new position to (0,0,0), but it 'freezes' before (example: I click space when sphere is at board's edge, then it freezes there, when I click arrow it go to new position and start going).
So, how to do that? I have no clue right now, although problem seems be easy.
Here a image with code and Unity with opened Inspector on object.
EDIT
I've a another problem.
Changed code as below (as Byte56 suggested):
if (Input.GetKeyDown(KeyCode.Space))
{
speed = 0;
rb.velocity = Vector3.zero;
rb.transform.position = new Vector3(0, 0.5f, 0);
rb.constraints = RigidbodyConstraints.FreezeAll;
speed = 1.0f;
}
if (moveHorizontal != 0 || moveVertical != 0)
{
rb.constraints = RigidbodyConstraints.None;
}
It seems like clicing space not always freezes object. It always put it on right place, but sometimes doesn't freeze. No matter if I use code rb.constraints = RigidbodyConstraints.FreezeAll;
or rb.Sleep();
- sometimes it works, sometimes not. I can't prove it, but it seems the smaller is delta of time between clicking space (smaller than 1 second) the chance that it won't freeze increases. It's not fault of space, I tried it with NumEnter.
Any idea? It seems really buggy.