Hello everybody.
I have the following case:
There is an object which follows the mouse on the screen. Rotates on Y axes with the following script:
// speed is the rate at which the object will rotate
var speed = 4.0;
function Update () {
// Generate a plane that intersects the transform's position with an upwards normal.
var playerPlane = new Plane(Vector3.up, transform.position);
// Generate a ray from the cursor position
var ray = Camera.main.ScreenPointToRay (Input.mousePosition);
// Determine the point where the cursor ray intersects the plane.
// This will be the point that the object must look towards to be looking at the mouse.
// Raycasting to a Plane object only gives us a distance, so we'll have to take the distance,
// then find the point along that ray that meets that distance. This will be the point
// to look at.
var hitdist = 100.0;
// If the ray is parallel to the plane, Raycast will return false.
if (playerPlane.Raycast (ray, hitdist)) {
// Get the point along the ray that hits the calculated distance.
var targetPoint = ray.GetPoint(hitdist);
// Determine the target rotation. This is the rotation if the transform looks at the target point.
var targetRotation = Quaternion.LookRotation(targetPoint - transform.position);
// Smoothly rotate towards the target point.
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, speed * Time.deltaTime);
}
}
And also I have a camera that follows that object as described in the code below.
// Pus pe camera
// Misca camera dupa target:
var target : Transform;
var distance = 10.0;
var height = 1.0;
var damping = 3.0;
var smoothRotation = true;
var rotationDamping = 5.0;
function Update () {
var wantedPosition = target.TransformPoint(0, height, -distance);
transform.position = Vector3.Lerp (transform.position, wantedPosition, Time.deltaTime * damping);
if (smoothRotation) {
var wantedRotation = Quaternion.LookRotation(target.position - transform.position, target.up);
transform.rotation = Quaternion.Slerp (transform.rotation, wantedRotation, Time.deltaTime * rotationDamping);
}
else
transform.LookAt (target, target.up);
}
When I try to move the object like “moving forward” I am facing the following problem: if the object is not rotated it moves ok on the desired direction, if it is rotated than it moves sideways, or any other way depending on how the object is rotated but always on the Z axis which “remains still” :).
My question is how can I make the object move forward on the direction that it is rotated to.
Thanks.