Search Unity

How do I make bullets move at an angle?

Discussion in 'Scripting' started by xXAl-HarereXx, Jul 15, 2020.

  1. xXAl-HarereXx

    xXAl-HarereXx

    Joined:
    Aug 21, 2017
    Posts:
    101
    So my character has 3 cannon tips to shoot from. The one in the middle goes straight right while the upper one goes upper right and the lower goes lower right. Currently all of them go straight right and I have no idea how to make the others move using their angles.
    In the code I'm just instantiating the bullets and moving them using this:
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class MoveObject : MonoBehaviour
    6. {
    7.     [SerializeField] float speed = 5f;
    8.     [SerializeField] bool towardsRight = true;
    9.  
    10.     Rigidbody2D rb;
    11.  
    12.     void Start()
    13.     {
    14.         //Moving Object Using Rigidbody
    15.         rb = GetComponent<Rigidbody2D>();
    16.         if(!towardsRight)
    17.         {
    18.             rb.velocity = new Vector2(-speed, 0);
    19.         }
    20.        
    21.         else
    22.         {
    23.             rb.velocity = new Vector2(speed, 0);
    24.         }
    25.     }
    26.  
    27.     public void setSpeed(float speed)
    28.     {
    29.         this.speed = speed;
    30.     }
    31.  
    32.     public void setTowardsRight(bool towardsRight)
    33.     {
    34.         this.towardsRight = towardsRight;
    35.     }
    36.  
    37.     public bool getTowardsRight()
    38.     {
    39.         return towardsRight;
    40.     }
    41.  
    42. }
    So I'm just using a speed value and adding it to the velocity.

    Capture.JPG


    Thanks for reading this :D
     
    Last edited: Jul 15, 2020
  2. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,775
    How are you shooting and moving your bullets currently? Post code
     
    xXAl-HarereXx likes this.
  3. xXAl-HarereXx

    xXAl-HarereXx

    Joined:
    Aug 21, 2017
    Posts:
    101
    Added in the thread :) Sorry
     
  4. WarmedxMints

    WarmedxMints

    Joined:
    Feb 6, 2017
    Posts:
    1,035
    You are only setting the x value of the velocity. Change speed to a float, angle the transforms they fire from, and then pass the direction of the transform and multiple it by the speed. For example;

    Code (CSharp):
    1. rb.velocity = cannon.transform.right * speed;