- Home /
Move a GameObject using Raycasting Hit position
var buildingObject : GameObject; var myGround : Transform;
function Update () { checkForBuilding(); }
function checkForBuilding() { var ray = Camera.main.ScreenPointToRay (Input.mousePosition); var hit : RaycastHit; if (Physics.Raycast (ray, hit, 100) && hit.collider.gameObject.CompareTag("Ground")){ //This is where i want to tell my buildingObject to move } }
I'm struggling to get my head around getting the buildingObject transform position to be where the raycasting has hit.
any suggestions on the simplest way of achieving this?
Thanks - C
Answer by efge · Feb 24, 2011 at 12:15 PM
With RaycastHit.point you get the position (Vector3) and with RaycastHit.normal the normal of the surface (also Vector3) witch you can use for rotation. But for buildings you should use no rotation. Then you could instantiate your building like this:
Instantiate(buildingObject, hit.point, Quaternion.identity);
Make sure your building is a prefab and the y-origin of it is 0.
Hey thanks for the reply. I don't want to instiate the building I want to simply snap the position of the building to the raytracing hit position.
Perfect thanks, I was just missing the .point. just a question on the side (for a vote up :D), is there a quick way to smooth the movement?
Take a look at the reference for the function Vector3.Lerp. There is a good example: http://unity3d.com/support/documentation/ScriptReference/Vector3.Lerp.html
Your answer
Follow this Question
Related Questions
Obstacle avoidance 1 Answer
2D Raycast not working 1 Answer
Problem with Unity Ray Trace AI Detect Player 0 Answers
why Physics.Raycast is not working 1 Answer