Search Unity

  1. The 2022.1 beta is now available for testing. To find out what's new, have a look at our 2022.1 beta blog post.
    Dismiss Notice

Throwing Object at 45 Incline, Strange Behavior

Discussion in 'Scripting' started by tpennetta, Jul 30, 2013.

  1. tpennetta

    tpennetta

    Joined:
    Jul 25, 2013
    Posts:
    18
    Hi all,

    I know this is a pretty basic question here. I am still getting my feet wet with Unity and 3D game programming.

    What I am trying to accomplish is the ability to throw an object from my character's hand. The object should be "tossed" at an upward angle in the direction of the target. Most of the script ran fine until I added the Quaternion rotation to have he item thrown "upward". What happens now it seems that the rotation is always based on the original location of the prefab where my character began in the level, or something weird like that. Can anyone see where I am going wrong here?

    Code (csharp):
    1.  
    2. public class ThrowItem : MonoBehaviour {
    3.    
    4.     public Transform _itemPrefab;
    5.     public float _throwForce = 2.0f;
    6.     public Transform _handPosition;
    7.     public Transform _target;
    8.    
    9.     // Use this for initialization
    10.     void Start () {
    11.    
    12.     }
    13.    
    14.     // Update is called once per frame
    15.     void Update () {
    16.         if (Input.GetKeyDown("b")) {
    17.             Transform thrownItem = Instantiate(_itemPrefab, _handPosition.position, Quaternion.identity) as Transform;
    18.             thrownItem.name = _itemPrefab.name;
    19.             thrownItem.LookAt(_target);
    20.             thrownItem.eulerAngles = Quaternion.Euler(0, 45, 0) * thrownItem.eulerAngles;
    21.            
    22.             thrownItem.rigidbody.AddRelativeForce(thrownItem.forward * _throwForce, ForceMode.Impulse);
    23.         }
    24.     }
    25. }
    26.  
     
unityunity