Search Unity

Throwing a object

Discussion in 'Scripting' started by StefanB95, Apr 17, 2011.

  1. StefanB95

    StefanB95

    Joined:
    Mar 14, 2011
    Posts:
    97
    So i wanna make like throwing a object that it moves from point a where he curenlty is to point b where the other player is and that only if range i tryed like this.
    the problem of my is that it goes to fast, and that its not if its only in range it can do it from everywhere
     
  2. billykater

    billykater

    Joined:
    Mar 12, 2011
    Posts:
    329
    1. Calling Update inside start isn't necessary: Start will be called only once at startup. Update will be called each frame
    2. Returning from start has no effect as update will be called nonetheless.
    3. Lerps third value should be in range from 0 to 1. I would recording the current time on startup like this

    Code (csharp):
    1.  
    2. var startTime : float
    3. function Start()
    4. {
    5.     startTime = Time.time;
    6. }
    7. function Update()
    8. {
    9.    transform.position = Vector3.Lerp(transform.position, end.position, (Time.time - startTime) / 5 );
    10. }
    11.  
    This will lerp over 5 seconds from 0 to 1
     
  3. Antony-Blackett

    Antony-Blackett

    Joined:
    Feb 15, 2011
    Posts:
    1,778
    To make it go slower scale the time you pass into Lerp

    This example will go at half the speed.
    Code (csharp):
    1.  
    2. // public script variables
    3. var speedScale = 0.5f;
    4. var timeSinceThrown = 0;
    5.  
    6. //this is inside Update
    7. timesinceThrown += Time.deltaTime;
    8. transform.position = Vector3.Lerp(transform.position, end.position, timeSinceThrown * speedScale  );
    9.  
    As for it doing it at any range, Update() gets called everyframe from the Unity engine if your script is a Unity MonoBehaviour. I'm assuming it is. What you'd be better off doing is checking the distance before the object is even created. Then this script only has to worry about movement and not the range.

    But if you want to do it this way then your Start function should set a boolean Thrown to true instead of calling Update() and then Update should check the boolean instead of its current condition.
     
    Last edited: Apr 17, 2011
  4. StefanB95

    StefanB95

    Joined:
    Mar 14, 2011
    Posts:
    97
    Just to ask so i don't need to call any function before i write a code or do i always need to do a function