- Home /
How to move a rigid body when you click on it
Hi I'm doing some kind of strategy game and I want a script so that when the first person controller clicks on an object with a rigid body on it, he can move around the object, so wherever the camera points the rigid body game object will move with it until the click button is released. I would really appreciate help. :) Thanks.
Answer by _1 · Mar 29, 2014 at 12:10 AM
#pragma strict
function Update()
{
var ray : Ray = camera.ScreenPointToRay (Input.mousePosition);
Debug.DrawRay (ray.origin, ray.direction * 10, Color.yellow);
var hit : RaycastHit;
if(Physics.Raycast(ray, hit))
{
if(hit.rigidbody && Input.GetMouseButton(0))
{
hit.rigidbody.AddForce(hit.transform.forward * 500);
}
}
}
this creates a ray from the camera and if the ray hits a rigid body and the mouse button is clicked, it will add force to rigid body
hope this is maybe what you were looking for and it helps :)
_1
can you mark it as an answer please by clicking on the green check mark next to the answers at the top of the answer that would help out a lot, I'm glad it helped :) Good luck with your game!
Your answer
Follow this Question
Related Questions
Move objects with mouse while paused (2D) 1 Answer
C# trying to move a object 2 Answers
Moving arrows far away from object 1 Answer
Object moving to mouse 0 Answers