Search Unity

2D Shooting Projectile in Movement Direction

Discussion in 'Physics' started by LionFische, Jan 27, 2016.

  1. LionFische

    LionFische

    Joined:
    Oct 16, 2015
    Posts:
    107
    Hi, I have a Player Character on a 2D plane. He can move in all directions. I have scripted so that he can launch a projectile. At the moment I am using the following code to launch.

    Code (CSharp):
    1. projectileInstance.AddForce(Launcher.right * projectileSpeed);
    I would however like to be able to launch in the direction the player object is moving. I'm not sure where to go with this and was wondering if some good solutions exist. I'm relatively new to Unity so am unfamiliar with most of it's functions.

    Full Script:

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class LaunchProjectile : MonoBehaviour {
    5.  
    6.     public Rigidbody2D projectile;
    7.  
    8.     public Transform Launcher;
    9.  
    10.     public float projectileSpeed = 5000f;
    11.  
    12.     // Use this for initialization
    13.     void Start () {
    14.      
    15.     }
    16.  
    17.     // Update is called once per frame
    18.     void Update () {
    19.         if (Input.GetButtonDown ("Fire1"))
    20.         {  
    21.             Rigidbody2D projectileInstance;  
    22.             projectileInstance = Instantiate(projectile, Launcher.position, Launcher.rotation) as Rigidbody2D;
    23.  
    24.             projectileInstance.AddForce(Launcher.right * projectileSpeed);
    25.         }      
    26.     }      
    27. }

    Thanks,
    2h
     
  2. jonathanvanry

    jonathanvanry

    Joined:
    Nov 14, 2014
    Posts:
    16
    I think you in AddForce you can use Launcher.rotation instead off Launcher.right.
     
  3. Hyblademin

    Hyblademin

    Joined:
    Oct 14, 2013
    Posts:
    725
    Make a reference to the player's Rigidbody2D in the above script. Then you can use Rigidbody2D.velocity.normalized to get a vector in the direction of motion in the current frame with a magnitude of 1. Multiplying that by your projectileSpeed should give the desired behavior.
     
  4. Splorange

    Splorange

    Joined:
    Jan 9, 2016
    Posts:
    1
    i just made an empty game object and flipped it