- Home /
Dragging Objects with the mouse
Hello,
I want to be able to move a Object with the mouse, like in a TowerDefense game adding turrets. I am just learning javascript so I dont know too much, The API is great, but I cant let it work, this is my current code: var turret : Rigidbody;
function Update () {
turret.transform.position = Input.mousePosition;
}
function OnMouseDown () {
var placement : Rigidbody;
placement = Instantiate (turret, transform.position, transform.rotation);
}
}
Answer by adrenak · Jan 07, 2012 at 06:42 PM
Why dont you try something like this? :
var turret : GameObject;
var viewHit : RaycastHit;
function Update(){
if(Input.GetButtonDown("Fire1"){
if(Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward), viewHit, 100)){ //100 is the range
Instantiate(turret, viewHit.point, Quaternion.identity);// instantiate the turret at the point where the raycast hits
}
}
}// update ends
This code should go to your camera that you use, the game object 'turret' can have a rigidbody component. Hope this helps! Tell me if it doesnt I am not on my comp right now so not 100% sure :)
right now it is just casting a ray from the camera down, but you really helped me, I just have to use something like $$anonymous$$ouseCursor.transform.position or something like that. I will have to consult the API(or script reference)
if it is casting from the mouse, then my mouse position is 800 meters in the air
Well, no- your mouse position is on the screen, not any actual point in 3d space! You need to use
Camera.main.ScreenPointToRay(Input.$$anonymous$$ousePosition);
to get the correct ray.
Yeah in the code that you have written there, turret.transform.position is a position vector in 3D space and Input.mousePosition is position in the screen co ordinates, you cant equate them directly.
Your answer
Follow this Question
Related Questions
Moving a object around with mouse, rotating it with arrow keys and placing it. 1 Answer
Detect a click outside a GUI/object 4 Answers
Object dissapears when moving fast 2 Answers
Animate an object 1 Answer
Animated Object moving when clicked 1 Answer