- Home /
Answer by robertbu · Aug 13, 2013 at 03:04 AM
Here are a few lines to get you started. Create a new scene, add your object, and add this script. 'lookFactor' should be between 0.1 and 1.0 and determines how extreme the look rotation.
#pragma strict
var lookFactor = 0.8;
function Update () {
var distance = (transform.position.z - Camera.main.transform.position.z) * lookFactor;
var position = Vector3(Input.mousePosition.x, Input.mousePosition.y, distance);
position = Camera.main.ScreenToWorldPoint(position);
transform.LookAt(position);
}
How can I alter this to make it instantly that rotation? I am spawning a prefab and I want it to spawn in with its front side pointing at the cords the mouse is pointing at.
The concept is the same. Here is a bit of code that instantiates a prefab at a random location and points the forward at the "mouse position."
#pragma strict
var prefab : GameObject;
var lookFactor = 0.8;
function Update () {
if (Input.Get$$anonymous$$ouseButtonDown(0)) {
var pos : Vector3 = Random.insideUnitCircle * 5.0;
var go = Instantiate(prefab, pos, Quaternion.identity) as GameObject;
var distance = (transform.position.z - Camera.main.transform.position.z) * lookFactor;
var position = Vector3(Input.mousePosition.x, Input.mousePosition.y, distance);
position = Camera.main.ScreenToWorldPoint(position);
go.transform.LookAt(position);
}
}