Car Movement scripting
Asked Answered
M

3

0

Hi all,

I want to make an object move like a car would - to make it so that the faster the car is moving the wider the turn angle and the slower the car is moving the smaller the turn angle.

Would anybody have any recommendations as to how to achieve this?

PlayerMove.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerMove : MonoBehaviour {
	public string Horizontal1;
	public string Vertical1;

	// Use this for initialization
	void Start () {
		
	}

	public Vector2 move;
	public Vector2 velocity; // in metres per second
	public float maxSpeed = 5.0f; // in metres per second
	public float acceleration = 5.0f; // in metres/second/second
	public float brake = 5.0f; // in metres/second/second
	public float turnSpeed = 30.0f; // in degrees/second
	private float speed = 0.0f;    // in metres/second

	// Update is called once per frame
	void Update () {

		// the horizontal axis controls the turn
		float turn = Input.GetAxis("Horizontal");

		// turn the car
		transform.Rotate(0, 0, turn * turnSpeed * Time.deltaTime);

		// the vertical axis controls acceleration fwd/back
		float forwards = Input.GetAxis("Vertical");
		if (forwards > 0) {
			// accelerate forwards
			speed = speed + acceleration * Time.deltaTime;

		}
		else if (forwards < 0) {
			// accelerate backwards
			speed = speed - acceleration * Time.deltaTime;

		}
		else {
			// braking
			if (speed > 0) {
				speed = speed - brake * Time.deltaTime;
			} else {
				speed = speed + brake * Time.deltaTime;
			}
		}

		
		// clamp the speed
		speed = Mathf.Clamp(speed, -maxSpeed, maxSpeed);

		// compute a vector in the up direction of length speed
		Vector2 velocity = Vector2.up * speed;

		// move the object
		transform.Translate(velocity * Time.deltaTime, Space.Self);
	}

}

Thanks!

Margrettmarguerie answered 21/7, 2023 at 21:32 Comment(1)

Hey i am a new user of Unity. I was searching around for car movement for my car. So i tried to put this in my script and do everything. But it doesnt work, my car just jumps and shakes. Can i please get some help

Milldam
M
0

Hey i am a new user of Unity. I was searching around for car movement for my car. So i tried to put this in my script and do everything. But it doesnt work, my car just jumps and shakes. Can i please get some help

Milldam answered 7/6, 2020 at 18:15 Comment(1)

Yes, I forgot while writing it here, it should be "public override void DoSomethingWhenHit()" in class EnemyController1

Oxymoron
I
0

try this way with your style

public float speed;
public float faster;
void Update()
{
      speed *= faster * Time.deltaTIme;
}
Indian answered 21/7, 2023 at 21:33 Comment(1)

Great, thanks.

Serrulation
F
0

Hi, I was looking for the same car movement as you posted here. So, I want to know that have you found the desired car control?

Fatherly answered 21/7, 2023 at 20:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.