Search Unity

  1. Get all the Unite Berlin 2018 news on the blog.
    Dismiss Notice
  2. Unity 2018.2 has arrived! Read about it here.
    Dismiss Notice
  3. Improve your Unity skills with a certified instructor in a private, interactive classroom. Learn more.
    Dismiss Notice
  4. ARCore is out of developer preview! Read about it here.
    Dismiss Notice
  5. Magic Leap’s Lumin SDK Technical Preview for Unity lets you get started creating content for Magic Leap One™. Find more information on our blog!
    Dismiss Notice
  6. Want to see the most recent patch releases? Take a peek at the patch release page.
    Dismiss Notice

Launching object in direction of mouse drag

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

  1. bugzilla

    bugzilla

    Joined:
    Dec 9, 2008
    Posts:
    187
    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.         mouseStartPosition = vRayStart.origin;
    28.     }
    29.  
    30.     void OnMouseUp()
    31.     {
    32.         mouseEndPosition = vRayEnd.origin;
    33.         heading = mouseEndPosition - mouseStartPosition;
    34.         distance = heading.magnitude;
    35.         direction = heading/distance;
    36.         Vector3 dragdirection = new Vector3(0.0f,direction.x,direction.y);
    37.  
    38.         rb.AddForce(dragdirection * fireForce,ForceMode.Impulse);
    39.     }
    40.     //-------
    41. }
    42.  
     
  2. dgoyette

    dgoyette

    Joined:
    Jul 1, 2016
    Posts:
    632
    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?