- Home /
Extremely simple car movement
Hello, I'm trying to make a game like Cubed Rally Racer which has very simple car movement like you can see in the video, I tried to look at the car tutorial and other answers here about cars but I couldn't find what I was looking for.
What I have at the moment is a simple cube, with a rigidbody and 1 of mass(it won't move with more than 1 of mass), and 4 spheres with wheel colliders on them under the cube and this is my movement script:
function Update () {
if (Input.GetKey(KeyCode.W))
rigidbody.AddForce (transform.forward * 100 * Time.deltaTime);
if (Input.GetKey(KeyCode.S))
rigidbody.AddForce (-(transform.forward) * 4*Time.deltaTime);
if (Input.GetKey(KeyCode.D))
transform.Rotate(0,1.5,0);
if (Input.GetKey(KeyCode.A))
transform.Rotate(0,-1.5,0);
}
It applies a force to the rigidbody to make it move forward, the "steering" is working but the car flips over as soon as it has some speed and it tries to steer, also the car won't stop moving once it has received some force (it seems like there's no friction). How do I make the car more stable and add friction to make it stop when it stops receiving force?
P.S I found out there's an online version of the game to see how the movement works: CubedRallyRacer
Not directly related to your question, but to save you headaches later, you should be applying forces during FixedUpdate() for the physics to be accurate.
As for slowing the car down, you could apply a force in the direction opposite to its velocity when nothing is pressed, although I'm sure there's a better way. Not had to do this myself yet (I want to play with the physics engine :( )
Answer by CosgunHalil · Jul 04, 2013 at 01:07 PM
2d movement script I used.
using UnityEngine;
using System.Collections;
public class carMove : MonoBehaviour {
float xspeep = 0f;
float power = 0.001f;
float friction = 0.95f;
bool right = false;
bool left = false;
public float fuel = 2;
// Use this for initialization
void FixedUpdate () {
if(right){
xspeep += power;
fuel -= power;
}
if(left){
xspeep -= power;
fuel -= power;
}
}
// Update is called once per frame
void Update () {
if(Input.GetKeyDown("w")){
right = true;
}
if(Input.GetKeyUp("w")){
right = false;
}
if(Input.GetKeyDown("s")){
left = true;
}
if(Input.GetKeyUp("s")){
left = false;
}
if(fuel < 0){
xspeep = 0;
}
xspeep *= friction;
transform.Translate(Vector3.right * -xspeep);
}
}
Your answer
Follow this Question
Related Questions
Better RPM?? 0 Answers
transmission clutch help! 1 Answer
Car Gearbox script 1 Answer
simple drift car movement 0 Answers
Car shifting effect? Help please! 1 Answer