- Home /
Setting rotation of instantiated object to that of a raycast?
The goal of my code is too find the angle of the exact point of where the ray cast hits and then instantiate an object there with the angle (x and y) of the hit point and rotate the new object accordingly. So far I have only attempted the Y angle and have failed miserably and have no idea why. All if does is spawn the object with no rotation just 0,0,0! Heres my code so far.
using UnityEngine;
using System.Collections;
public class Build : MonoBehaviour
{
public Ray ray;
public RaycastHit hit;
public GameObject Piece;
public Object clone;
public float range = 10;
void Update(){
if (Input.GetButtonDown("Fire1")){
Place();
}
}
void Place(){
ray = Camera.main.ScreenPointToRay (Input.mousePosition);
if (Physics.Raycast (ray,out hit, 100)) {
Debug.DrawLine (ray.origin, hit.point);
Rigidbody clone;
clone = Instantiate(Piece,hit.point,Quaternion.identity) as Rigidbody;
clone.transform.up = hit.normal;
Vector3 rotation = clone.transform.localEulerAngles;
rotation.y = transform.localEulerAngles.y;
clone.transform.localEulerAngles = rotation;
}
}
}
Sorry for the weird formatting of the code. I dont know why but even when I edit I cant fix it.
Answer by Owen-Reynolds · Feb 01, 2012 at 06:13 PM
clone.transform.LookAt(hit.normal);
will aim it along the normal. In general, LookAt(someDirection) is the simplest way to set a rotation. Also look at the optional second input for setting "up".
The problem is that rotation is done with Quaternions, not angles. There's a conversion if you know all angles: rotation=Quaternion.Euler(0,90,0);
. But setting or examining the x,y,z angles one at a time does unpredictable things.