Search code examples
vectorpositionunity-game-engine2dunityscript

Moving a 2d object towards and through a position in Unity 4.3


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));

}

Solution

  • 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.