- Home /
Move selected object
hi guys i am using a following script to move an object with mouse click but my problem is all the objects move on mouse click. So what can i add to my code so that first on mouse click objects gets selected and highlighted..then on another click it moves to mouse position.I have searched a lot but cannot find solution.Also i want that when i click anywhere else or on another object ..the previously selected objects gets deselected.Thanks
var obj:Transform;
private var hitPoint : Vector3;
private var move: boolean = false;
private var startTime:float;
var speed = 1;
function Update ()
{
if(Input.GetKeyDown(KeyCode.Mouse0))
{
var hit : RaycastHit; // no point storing this really
var ray = Camera.main.ScreenPointToRay (Input.mousePosition);
if (Physics.Raycast (ray, hit, 10000))
{
hitPoint = hit.point;
move = true;
startTime = Time.time;
}
}
if(move)
{
obj.position = Vector3.Lerp(obj.position, hitPoint, Time.deltaTime * speed);
if(obj.position == hitPoint)
{
move = false;
}
}
}
Answer by robusto · Jun 14, 2014 at 02:25 PM
I think you are mostly there. Let me try and think your process through without giving away the whole thing.
If Mouse0 button is down, raycast and if hit, set the hit.collider.gameObject to a gameObject var. If there was no hit, set your gameObject var to null.
If Mouse1 button is down and your gameObject var is not null, set bool move var to true and raycast into the ground and set the hitpoint.
If bool move var is true, lerp the gameObject's position to the hitPoint and set bool move var to false once done.
Another thing I noticed is that when you use the Lerp function, the last parameter isn't your speed, but it is percent, a value between 0 and 1. You should hold a var float percent somewhere, set it to 0, when you start lerping increment it using percent += speed * time.deltatime, and to check if you are done, use if( Mathf.Approximately( 1f, percent ) )
hey thanx man for the answer i will try that and can you please give me the code for the last thing you said about lerp function.
Your answer
Follow this Question
Related Questions
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
click to move with constant speed 2 Answers
Assigning valid moves 0 Answers