Hey so I’m working on a car game, and I have a script that accelerates the car up to max speed gradually and at the moment I’m trying to add turning to it, but instead of turning the force that is being applied, it just rotates the object as it goes in a straight line.
I’m not sure how to add force to the objects z axis (which stays the same doesn’t it?) so that even if the car is turning then it will add force in the right direction.
All help is appreciated, here’s the script without any turning on it.
maxVelocity = 50.0;
var movement = 100;
function FixedUpdate(){
var throttle = Input.GetAxis("Vertical");
if (throttle != 0){
rigidbody.AddForce(0, 0, throttle * movement);
}
if (rigidbody.velocity.z > 50.0){
rigidbody.velocity.z = maxVelocity;
}
if (Input.GetKey("space")){
rigidbody.velocity.z /= 2;
}
}
Arachnos, just FWIW, it’s really not that easy to make a vehicle. It’s really quite a lot of work. I’ve not seen a half-decent vehicle done in less than, oh, 100, 200 lines of code (perhaps more).
In general, the approach you’re taking (just adding force to “the car”) really won’t work other than for just a trivial test presentation, you know. You, generally, have to add force on the wheels, in some sense.
Fortunately, there are a number of “vehicle kits” in the Asset store - just buy one and your project is finished, if you’re just trying to knock together a car that works reasonably. Or, fool with the car-tutorial from Unity above.
Again if you look at the example download from Unity above, you will see it is really quite a lot of physics to get a car going, even in a basic manner.
Just FWIW in the example code you posted, (1) as a general rule you never alter the velocity of a rigidbody. In your braking code there, you would just add force in the backwards direction. (2) to make a simple sort of “trivial car” like you have actually turn left or right probably the best bet is to add a force pointing left or right, to points on the outside front of the car (indeed, you might as well use the front two wheels) - but it’s really not gonna help you much as you’ll eventually have to sit down and make “a more proper vehicle” probably using wheel colliders and so on.
Sorry for the bad news! Like I say download Unity’s car example, and you’ll get an idea how much annoying code is involved and how to proceed. Hope it helps