Help car drive forward using rigidbidy
Help! I'm trying to get my car to drive forward (in the direction i'm facing) when pressing w. Unfortunately so far I've only been able to add an upwards force to the car so far using the below code. Sorry it's messy. Any advice would be great.
This is the main movement code: car.GetComponent().AddForce(forward, ForceMode.Acceleration);
(forward is something detailed below)
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class Drive : MonoBehaviour { public GameObject car; Vector3 rotation;
//Vector3 velow;
float velox;
float veloy;
float veloz;
// Start is called before the first frame update
void Start()
{
}
private void Update()
{
//velow = this.gameObject.GetComponent<Rigidbody>().velocity.w;
velox = car.gameObject.GetComponent<Rigidbody>().velocity.x;
veloy = car.gameObject.GetComponent<Rigidbody>().velocity.y;
veloz = car.gameObject.GetComponent<Rigidbody>().velocity.z;
}
void FixedUpdate()
{
Vector3 myvelocity = new Vector3(velox, veloy, veloz);
rotation = this.gameObject.transform.eulerAngles;
Vector3 forward = Vector3.RotateTowards(rotation, Vector3.left,0f, 1f);
//Vector3 direction = rotation * Vector3.forward;
if (Input.GetKey(KeyCode.W))
{
//this.gameObject.transform.Translate(Vector3.forward * Time.deltaTime * 10);
car.GetComponent<Rigidbody>().AddForce(forward, ForceMode.Acceleration);
//car.GetComponent<Rigidbody>().AddForce(rotation * ForceMode.Acceleration);
//car.GetComponent<Rigidbody>().AddForce(direction, ForceMode.Impulse);
}
Your answer
Follow this Question
Related Questions
why the camera rotate in the z axis 0 Answers
Can't seem to find a proper stepping stone to learn from, any ideas? 3 Answers
Best way to learn how to utilize the Unity API? 2 Answers
How to learn Unity C# better and faster? 2 Answers
How do I get a reference to a script that is on another gameobject 0 Answers