I’m trying to rotate a model to align parallel with the road. I have some code that keeps showing perpendicular angles.
i’m not sure if i have the right angles calculated.
//rotate to road angle
RaycastHit hit;
Physics.Raycast(transform.position, transform.up, out hit, 20f);
float xy = Vector2.Angle(new Vector2(hit.point.x, hit.point.y), new Vector2(transform.position.x, transform.position.y));
float xz = Vector2.Angle(new Vector2(hit.point.x, hit.point.z), new Vector2(transform.position.x, transform.position.z));
float yz = Vector2.Angle(new Vector2(hit.point.y, hit.point.z), new Vector2(transform.position.y, transform.position.z));
gameObject.GetComponent<Rigidbody>().MoveRotation(Quaternion.Euler(new Vector3(xy, yz, xz)));
heres the full code…
I want the model to align with the ground transform. Also my model doesn’t turn with turnTorque.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class carController : MonoBehaviour {
public float acceleration;
public float rotationRate;
public float turnRotationAngle;
public float turnRotationSeekSpeed;
private float rotationVelocity;
private float groundAngleVelocity;
private float ROTvel;
private float rotvel2;
void Update(){
}
// Update is called once per frame
void FixedUpdate () {
//forward Force
Vector3 forwardForce = transform.forward * acceleration * Input.GetAxis("Vertical");
forwardForce = forwardForce * Time.deltaTime * gameObject.GetComponent<Rigidbody>().mass;
gameObject.GetComponent<Rigidbody>().AddForce(forwardForce, ForceMode.Force);
//GameObject.Find("engine").GetComponent<Rigidbody>().AddForce(forwardForce, ForceMode.Force);
//turn Velocity
Vector3 newRotation = transform.rotation.eulerAngles;
newRotation.y = Mathf.SmoothDampAngle(newRotation.y, Input.GetAxis("Horizontal")*turnRotationAngle, ref rotationVelocity, turnRotationSeekSpeed);
//rotate to road angle
RaycastHit hit;
Physics.Raycast(transform.position, transform.up, out hit, 20f);
Vector3 hitn = hit.normal;
float hitx = Vector3.Angle(new Vector3(0,hit.collider.transform.rotation.eulerAngles.y,0), new Vector3(0,0,hit.collider.transform.rotation.eulerAngles.z));
float hity = Vector3.Angle(new Vector3(hit.collider.transform.rotation.eulerAngles.x,0,0), new Vector3(0,0,hit.collider.transform.rotation.eulerAngles.z));
float hitz = Vector3.Angle(new Vector3(0,hit.collider.transform.rotation.eulerAngles.y,0), new Vector3(hit.collider.transform.rotation.eulerAngles.x,0,0));
//gameObject.GetComponent<Rigidbody>().AddTorque(new Vector3(hitn.x*transform.rotation.eulerAngles.x, transform.rotation.eulerAngles.y, hitn.z*transform.rotation.eulerAngles.z));
//Turn Model
Vector3 turnTorque = Vector3.up * rotationRate * Input.GetAxis("Horizontal");
turnTorque = turnTorque * Time.deltaTime * gameObject.GetComponent<Rigidbody>().mass;
gameObject.GetComponent<Rigidbody>().AddTorque(turnTorque);
}
}