- Home /
Boat movement, driving and animation
I'm trying to make a player-controllable boat and I'm running into problems with my code.
1) I want to make the boat to accelerate and decelerate steadily instead of simply moving the speed I'm telling it to right away.
2) I want to make the player unable to steer the boat unless it is moving.
3) I've animated an idle animation of my boat floating around, but when the animation is playing, my boat can't move. What can I do to eliminate that?
My current code (C#) is this:
using UnityEngine; using System.Collections;
public class VehicleScript : MonoBehaviour {
public float speed=10;
public float rotationspeed=50;
// Use this for initialization
// Update is called once per frame
void Update () {
// Forward movement
if(Input.GetKey(KeyCode.I))
transform.Translate (Vector3.left*speed*Time.deltaTime);
// Backward movement
if(Input.GetKey(KeyCode.K))
transform.Translate (Vector3.right*speed*Time.deltaTime);
// Left movement
if(Input.GetKey(KeyCode.J))
transform.Rotate (Vector3.down*rotationspeed*Time.deltaTime);
// Right movement
if(Input.GetKey(KeyCode.L))
transform.Rotate (Vector3.up*rotationspeed*Time.deltaTime);
}
}
In the current state of my code, when I press the specified keys, the boat simply moves 10 units/sec instantly, and also stops instantly. I'm not really sure how to make the things stated above, so any help would be appreciated. Just to clarify, I don't necessarily need the full code to implement those features, I just want to know what functions to use in order to achieve the desired effects.
Thank you very much.
Answer by supernat · Aug 23, 2014 at 07:20 AM
This is a physics problem. You just need to store the velocity in a local variable, and add to it or subtract from it each frame. For instance, if they hit the forward button, you increase the local velocity variable by time.deltaTime*acceleration where acceleration is some constant you define. Then if they don't press anything, you would want to reduce the velocity, probably by a smaller deceleration.
Making the boat not move when it's standing still is easy. Just call Rotate(speed*angularRate*time.deltaTime) where angularRate is a constant, and speed is the magnitude of the previously computed velocity. So when the boat's velocity reaches 0, it stops rotating, and it actually rotates faster as the velocity increases. If it rotates too fast, use speed/2 or more. If you want it non-linear, sqrt(speed).
Lastly, Translate by the velocity vector.
So, in this order:
1) Increase/Decrease velocity based on forward/backward/no input
2) Limit velocity to some min and max
3) Rotate by the magnitude of the velocity based on left/right
4) Translate by the velocity
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
I need help with my pause menu 1 Answer
C# wait X-Seconds in Code before continue in Code? 3 Answers