- Home /
how do i spawn an object x units from a hit in the racyastHit normal's direction
hello everyone, i am not sure how understandable is the title of this question. anywhay ill do my best to explain a little better. i want to instantiate an object the way the diagram below sort of represents:
|../
|./ <--- raycast
|/
|----O <---(object)
|
|<--- surface hit
i want to know what is the Vector3 at which the object spawns, i know how to get the normal of the hit and the position at which it hit, but what i do not know is how to get the vector3 where the object would be spawned, and that is what i dont know how to get.
i want to let you know i do not want you guys to write any code for me other than maybe some exaple, but if possible to explain how would you do this.
thank you all very much in advanced.
Answer by clunk47 · Feb 11, 2014 at 12:29 AM
In this C# Example, I attach the script to the main Camera. For testing, I placed some cubes in random positions somewhere in front of the camera. Each time you click on a cube in the scene, this will instantiate your assigned prefab halfway between your Camera and the object you're clicking on.
using UnityEngine;
using System.Collections;
public class Example : MonoBehaviour
{
Ray ray;
RaycastHit hit;
public GameObject prefab;
void Update()
{
ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if(Physics.Raycast(ray, out hit) && Input.GetMouseButtonDown (0))
{
GameObject clone = Instantiate(prefab, Vector3.Lerp(transform.position, hit.transform.position, 0.5F), hit.transform.rotation) as GameObject;
}
}
}
Answer by highpockets · Feb 11, 2014 at 12:19 AM
Well if you have the position at which you send the raycast from. For example, if you were to send it from the camera, you store that position:
(Assuming the script is on the camera)
Vector3 castPos = transform.position
And you said you have the normal position. So just get the difference of the 2 Vectors and divide by 2:
Vector3 diff = castPos - normalPos;
Vector3 targetPos = diff / 2; //instantiate here
Sorry my calculation won't work!! Oops.. I was thinking that you could simply use Vector3.Lerp though:
Vector3.Lerp( castPos, normalPos, 0.5f );
That should return the halfway Vector3 position that you want to instantiate at. The Lerp function will give you the castPos at 0.0f and the normalPos at 1, so, 0 - 1 is like 0-100% of the distance
Your answer
Follow this Question
Related Questions
Health System Raycast Bullets 2 Answers
Perspective issue with railgun/raycasting 0 Answers
Prevent Raycast on reacting to GUI input? 2 Answers
Why Raycast is not working properly? 0 Answers