Search Unity

Launching object in direction of mouse drag

Discussion in 'Physics' started by bugzilla, Jul 13, 2018.

  1. bugzilla

    bugzilla

    Joined:
    Dec 9, 2008
    Posts:
    196
    I am trying to make a 3D physics game where you flick balls in the direction of your mouse drag. I have this script but it only seems to work in the vertical direction. Any ideas?

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class DragToLaunch : MonoBehaviour {
    6.     public float    fireForce;
    7.     public Vector3     mouseStartPosition;
    8.     public Vector3     mouseEndPosition;
    9.  
    10.     public Vector3    heading;
    11.     public float    distance;
    12.     public Vector3    direction;
    13.  
    14.     public Rigidbody rb;
    15.     // Use this for initialization
    16.     void Start () {
    17.         rb = this.GetComponent<Rigidbody> ();
    18.     }
    19.    
    20.     // Update is called once per frame
    21.     void Update () {
    22.        
    23.     }
    24.  
    25.     void OnMouseDown()
    26.     {
    27.         Ray vRayStart = Camera.main.ScreenPointToRay(Input.mousePosition);
    28.         mouseStartPosition = vRayStart.origin;
    29.     }
    30.  
    31.     void OnMouseUp()
    32.     {
    33.         Ray vRayEnd = Camera.main.ScreenPointToRay(Input.mousePosition);
    34.         mouseEndPosition = vRayEnd.origin;
    35.         heading = mouseEndPosition - mouseStartPosition;
    36.         distance = heading.magnitude;
    37.         direction = heading/distance;
    38.         Vector3 dragdirection = new Vector3(0.0f,direction.x,direction.y);
    39.  
    40.         rb.AddForce(dragdirection * fireForce,ForceMode.Impulse);
    41.     }
    42.     //-------
    43. }
    44.  
     
  2. dgoyette

    dgoyette

    Joined:
    Jul 1, 2016
    Posts:
    4,196
    Any reason why you're using ScreenPointToRay, instead of just Input.mousePosition? It seems like you're really only interested in the mouse position during the Down and Up events.

    Is your camera pointing down? Your DragDirection vector also looks a bit odd to me. You're using the `x` component of your direction vector into the `y` component of your force Vector. Is your camera in a weird orientation?
     
  3. bugzilla

    bugzilla

    Joined:
    Dec 9, 2008
    Posts:
    196
    Actually, it was the only code I could find from all the research I did that matched what I was trying to do. I experimented with putting the X and Y coordinates into the X,Y,Z components of the Force vector but so far no luck.

    It seems like a common thing to do in any physics based game so I am surprised there is not sample code floating around for this type of event already.