- Home /
Rotating a object towards a direction then move it
Hi normally just searching the forums / unity docs or googling around can solve my programming issues but i've been stuck for about the last month and i'm on the fourth attempt at making a basic tank controller with each attempt i'm getting closer and closer but right now I am just stuck.
My problem isn't with moving it but making it rotate towards the direction the player whats to travel then moving. I provided two videos to show what im trying to accomplish
What I want http://youtu.be/9zrxS0LcnRo
What I currently have http://youtu.be/8FSPA7863-c
Currently it rotates but doesn't stop when it faces forward and so and endless rotation occurs until you stop pressing forward
public class attempt4 : MonoBehaviour
{
Quaternion qtarget; //quartnon target ie rotation
public Transform waypoint; //the cube in front of the tank
public Transform Turrent_pos; //the top turrent of the tank
public float rspeed = 10; //turn speed of tank
public float speed = 8; //forward speed
public bool tankBody = false;
void LateUpdate()
{
//Quaternion deltaRotation = Quaternion.Euler(waypoint.transform.position-transform.position);
//rigidbody.MoveRotation(Quaternion.Slerp(rigidbody.rotation, deltaRotation, rspeed * Time.deltaTime));
qtarget = Quaternion.LookRotation(waypoint.transform.position-transform.position); //non ridgid body quatornon
// based on input, determine requested action
if (Input.GetAxis("Vertical") > 0)
{
// requesting forward
transform.rotation = Quaternion.Slerp(transform.rotation, qtarget, rspeed * Time.deltaTime); //this rotates the object towards the waypoint(direction camera is facing)
transform.position+= (transform.TransformDirection(Vector3.forward) * speed * Time.deltaTime); //this rotates the object to the direction we need to travel multiply by speed, progressed by time
}
else if (Input.GetAxis("Vertical") < 0)
{
// requesting reverse
transform.rotation = Quaternion.Slerp(transform.rotation, qtarget, rspeed * Time.deltaTime);
transform.position-= (transform.TransformDirection(Vector3.forward) * speed * Time.deltaTime);
}
}
}
Is there anyway i could make it wait until the tank is relatively facing forward and then allow it to move?
try setting some condition like
var turretIsRotating : boolean;
//then something like
if(turretIsRotating) {
//your code here
}else{
}
using boolean can help you a lot in tricky situations.
Thanks for the help, I got it working I used rotatetowards ins$$anonymous$$d of LookAt which is a close secound in combination with the booleans