I have calculated and rotated an object to face the desired direction of travel and want to propel it directly in the direction it is facing…

I understand if I give the object a rigid body that I can go about this by means of AddForce, or AddRelativeForce… But really I would rather manipulate the object by means of Transform…

What is the best way of doing this…

Thanks…

Here is the code I have…

``````using UnityEngine;
using System.Collections;
public class V2MovePlayerToRabbit : MonoBehaviour {
public Transform HomeRabbit4; // Linking this game object to the rabbit position
private float Diffx;
private float Diffz;
private float MoveDirection;
// Update is called once per frame
void Update () {
// Diffx and z are variables required to calculate desired angle
Diffx = gameObject.transform.position.x - HomeRabbit4.position.x;
Diffz = gameObject.transform.position.z - HomeRabbit4.position.z;
//Calculate the desired taget angle
MoveDirection = Mathf.Atan2 (Diffx, Diffz) * 180 / Mathf.PI;
print ("Move Direction = " + MoveDirection + "degrees");

// Set the player facing it's intended target
transform.Rotate (0, MoveDirection, 0);

// Now the player is facing its intended target we must
// add a force along the "FORWARD" axis relative to the new rotation...
// We can limit the speed this object is allowed to transform at directly with a variable ie "MAX SPEED"
// We also need to factor in Time.deltaTime so this calculation is not affected by current Frame-rate

}

}
[code/]

Thanks
``````

Haha! Well, I now also see that I am in fact adding that rotation every frame, thus achieving the spinning spiral of AI Doh!

I have sussed the transform.Translate (1, 0, 0 * Time.Deltatime) to get it moving… Only now I need to find a way of making that rotation figure correct

You might want to just use transform.LookAt.
You’ll want to move your target to the same Y if you don’t want any tilting.

wouldn’t the principal be the same? Just add (transform.forwardvelocitytime.delta)?

edit - more specifically, I think you’d want something like (targetpos-sourcepos).normalizevelocitytime.delta

I researched and found .LookAt late last night… It effectively does the calculation for me… Thus turning a 20 line code into 2…!

First thing I noticed was the transform slowly pushing my object through the floor… Tilting Solved that issue by ensuring the Rabbit (Target) has the same Y plane…

I would like to know if the ‘LookAt’ function is more or less costly than what I initially coded… It seems when calling such function (They look so easy!) But behind the scenes the UNITY engine is doing the hard work, just it cant be seen!

I also have read that using any ‘.position’ is really bad for performance as effectively the unity engine IS doing a GetComponent.Transform.position without you seeing it - Is this really the case?

Also I have been made aware of using a cache for these situations, although I don’t yet fully understand!

Thanks again for the support

Peace…