Question by 
               BSacramento · Mar 22, 2018 at 11:28 AM · 
                2d-platformerraycasthit2d  
              
 
              Throw a object in the direction of the mouse
I have a script that grabs an object and throws it in the direction that the player is facing (game in 2D), but i want to throw it in the direction of the mouse and i cant understand how that will work, any help?
using UnityEngine; using System.Collections;
public class grabberscript : MonoBehaviour {
 public static bool grabbed;
 RaycastHit2D hit;
 public float distance=2f;
 public Transform holdpoint;
 public float throwforce;
 public float throwforceBack;
 public LayerMask notgrabbed;
 float lockPos = 0;
 void Start () {
 }
 void Update () {
     if(Input.GetKeyDown(KeyCode.P))
     {
         
         if(!grabbed)
         {
             Physics2D.queriesStartInColliders=false;
             hit =    Physics2D.Raycast(transform.position,Vector2.right*transform.localScale.x,distance);
             if(hit.collider!=null && hit.collider.tag == "grabbable")
             {
                 grabbed=true;
             }
                 
         }else if(!Physics2D.OverlapPoint(holdpoint.position,notgrabbed))
         {
             grabbed=false;
             if(hit.collider.gameObject.GetComponent<Rigidbody2D>()!=null)
             {
                 if (SimplePlatformerController.facingRight)
                 hit.collider.gameObject.GetComponent<Rigidbody2D>().velocity= new Vector3(transform.localScale.y, 1)*throwforce;
                 if (SimplePlatformerController.facingRight == false)
                 hit.collider.gameObject.GetComponent<Rigidbody2D>().velocity= new Vector3(transform.localScale.y, -1)*throwforceBack;
                     
             }
         }
     }
     if (grabbed)
     {
         hit.collider.gameObject.transform.position = holdpoint.position;
         hit.collider.transform.rotation = Quaternion.Euler (transform.rotation.eulerAngles.x, lockPos, lockPos);
     }
 
              
               Comment
              
 
               
              Your answer
 
             Follow this Question
Related Questions
RaycastHit2D normal returns raycast in opposite direction, not surface normal. 1 Answer
Need help making a ledge climber. The problem, transform.position always returns to vector( 0, 0) 0 Answers
Vertical Rays rapidly changing between "detecting ground" to "not detecting ground" 0 Answers
How to Raycast 2D Diagonally instead of Horizontal on a Platformer game. 0 Answers