Reputation: 901
Trying to get an object to fire towards and through a given position. Like a bullet firing towards the mouse location, I don't want it to stop on the mouse (which is what is happening now).
Below is what I have so far, is there a function like lerp that I could use?
var speed:float;
var startPoint:Vector3;
var startTime:float;
var clickedPosition:Vector3;
function Start()
{
startPoint = transform.position;
startTime = Time.time;
clickedPosition = Vector3(Input.mousePosition.x, Input.mousePosition.y, 0);
clickedPosition = Camera.main.ScreenToWorldPoint(clickedPosition);
}
function Update ()
{
transform.position = Vector3.Lerp(startPoint, clickedPosition, (Time.time-startTime));
}
Upvotes: 2
Views: 13455
Reputation: 619
This is pretty simple. You can use the Vector3.Lerp function to achieve this. Use raycasting to get the mouse click position or the touch position. Then use the initial and the final position in the lerp function. The initial position being the position that the gameobject is at now and the final position being the click / touch position. You can find the article on the same here
Move to Touch / Click Position - The Game Contriver
Upvotes: 1
Reputation: 278
var speed:float;
var startPoint:Vector3;
var startTime:float;
var clickedPosition:Vector3;
function Start()
{
startPoint = transform.position;
}
function Update ()
{
if(Input.GetKeyDown(KeyCode.Mouse0))
{
startTime = Time.time;
clickedPosition = Vector3(Input.mousePosition.x, Input.mousePosition.y, 0);
clickedPosition = Camera.main.ScreenToWorldPoint(clickedPosition);
}
transform.position = Vector3.Lerp(startPoint, clickedPosition, (Time.time-startTime));
}
Upvotes: 1
Reputation: 627
I would suggest using a rigidbody component and then applying a force in the direction (while disabling gravitiy i guess).
The way you have it now you should probably get it to work with
var speed : float;
function Start()
{
speed = 1000.0f; // experiment with this, might be way too fast;
...
}
function Update()
{
transform.position += (clickedPosition - startPoint) * speed * Time.deltaTime;
}
(clickedPosition - startPoint) should give you the direction in which you want to move the object, Time.deltaTime gives you the milliseconds since the last call of the Update function (you want this in here so that the object moves the same speed at different framerates) and speed is just a constant to adjust the velocity.
Upvotes: 2