(I just wrote a huge wall of text for like 5 minutes and when I tried to post it, it all was just deleted, so I have to type everything out again, and now it's going to be shorter...)
I am on my second day of learning Unity and are currently doing the roll-a-ball tutorial. I am trying to add a restart button, that teleports the ball back to the start position. It all works good, but the ball will keep moving after I restart, but I want it to stay in a spot and not move by itself.
What I mean is that if I'm moving left at max speed and press 'R' to restart, then it will keep moving left fast for some time.
Here's my code that I just tried out and "hoped" would work, but I think that the problem I have here is that the GetAxis doesn't get restarted, and the next frame after the restart new AxisHorizontal/Vertical values will be assigned and so will AddForce:
using UnityEngine;
using System.Collections;
public class PlayerScript : MonoBehaviour {
public float movementSpeed = 7f;
private Rigidbody rigidSphere;
void Start() {
rigidSphere = GetComponent();
}
void FixedUpdate() {
float axisHorizontal = Input.GetAxis("Horizontal");
float axisVertical = Input.GetAxis("Vertical");
Vector3 movementForce = new Vector3(axisHorizontal, 0.0f, axisVertical);
rigidSphere.AddForce(movementForce * movementSpeed);
if (Input.GetKeyDown(KeyCode.R)) {
transform.position = new Vector3(0, 0, 0);
rigidSphere.AddForce(0, 0, 0);
axisHorizontal = 0;
axisVertical = 0;
}
}
}
I tried googling on how to change the value that is taken from GetAxis, but others claim it's impossible to do so. So I have really no idea how to make it not keep moving forever...
And I also got two 'bonus' questions that have arised during those two days that I have been learning Unity, but they are not worth a new thread.
First, how do I make the ball stop moving after some time after I press a button? For example, I press 'W' just for a second, but the ball will keep moving forward forever and will never stop.
What I want to achieve is after I for example press 'W' for a second, after a few seconds the ball will completely stop, it just seems that the value from GetAxis never goes back to 0. I tried to google about it, and I think it's something to do with Gravity in the Input Manager - I tried changing it, but no results.
And the second question is how I "pause time" in code, I googled and found out I have to use something like WaitForSeconds() and IEnumerator, but I couldn't do it, the docs didn't help neither.
I'd be really grateful if someone could help me with these problems.
↧