- Home /
Moving forward in 3D
How can I move target directly where is camera looking at ? Is there any script in Unity or how can I create script for this ? Thx
The answer will depend on how your are moving your object, and at what distance from the camera do you want to calculate the point. Unity is 3D, so if we project a vector from the center of the camera forward, there will be an infinite number of points (conceptually) that the camera is looking at. So you have to decide how far in front of the camera you want to calculate the point.
Answer by robertbu · Oct 01, 2013 at 08:27 PM
Again, it will depend on how you are moving the object. For a Character Controller:
cc.Move(Camera.main.transform.forward * speed * Time.deltaTime);
For a transform:
transform.position += Camera.main.transform.forward * speed * Time.deltaTime;
For a Rigidbody (in FixedUpdate()):
rigidbody.velocity = Camera.main.transform.forward * frameSpeed;
This assumes as in the video that the camera keeps the object at the center of the screen.
thx....this helped me too but i want to specify my question...it should look like this video
Assu$$anonymous$$g you have the camera movement code, the following script will cause the object to behave like in the video. Note it directly manipulate the transform, which may or may not be the way you want to handle the object. It depends on the nature of the rest of your game. Set distFromCamera to the distance you want your object in front of the camera. Note as with the video, the object is not rotated to face the direction of movement.
#pragma strict
var distFromCamera = 3.0;
private var cam : Transform;
function Start() {
cam = Camera.main.transform;
}
function Update() {
transform.position = cam.position + cam.forward * distFromCamera;
}
Whatever camera movement code you want to use, the script I just posted will cause the object to behave like the video.