Unity Shooting Arrows in Top Down Perspective Part 1 – Tutorial


What’s up Game Developers? CouchFerret here, and today we’ll continue our archery game with our script to Shoot Arrows. We’ll Instantiate arrows
from a Prefab, and give them Velocity to move towards the enemy. Because this topic is a bit
bigger, I’ve broken it into two parts, so come back next Wednesday for part 2! If it sounds fun, then stay with me, and consider subscribing so you won’t miss any future videos of this game. Cool, let’s begin! First, need to draw the arrow before we can shoot it.
Let’s fire up Aseprite, the pixel art editor I use, and start drawing! When we finish,
we need to export it as a png for Unity. Let’s save it directly to our project’s directories.
Now in Unity, we can see that it’s a bit blurry. We have to set Filter Mode to Point (no filter)
and Compression to None, then hit Apply. Much better! Dragging and Dropping the Sprite into
the scene we can create an arrow GameObject. Unity automatically adds a Sprite Renderer
Component to it as well. To make arrows from script in the future, we need to create a
template for Unity to know what exactly an arrow is made of. In Unity, this template
is called a Prefab. Before we do anything, let’s create a folder for Prefabs. We can
create a Prefab by right clicking on the Project window and selecting Create/Prefab. This Prefab
will be empty, so we need to drag a Gameobject into it. However, it’s easier to just drag
and drop the gameobject from the scene into the Project window. Now, we have our arrow
Prefab, so we can delete the arrow gameobject we have in the scene. Let’s jump into the
code! We have to declare a variable for the arrow Prefab, to refer to it when we make
a copy of it. Save the code, and let’s fill the variable by selecting Keith and dragging
the Prefab from the Project window into the Player Controller script’s Arrow Prefab variable.
Notice the difference in the icons between a GameObject like the CrossHair and a Prefab
like the Arrow. Okay, let’s continue our script! From a previous episode, we have this if statement
to check whether we press the A button on an Xbox Controller or not. Now, we only print
out a Debug message which says FIRE!, so let’s change it to something a little more exciting.
We can make a copy of a Prefab by calling the Instantiate() function. Let’s type Instantiate(arrowPrefab,
transform.position, Quaternion.identity);. The first argument is the object we want to
make a copy of, the second its initial position, and the third is its starting orientation
or rotation. In our case the object is our arrow Prefab, the position is the archer’s
current position, and the orientation is the identity which means there is no rotation.
Let’s try it out! If I fire, then a bunch of arrows appear in the scene. The script
we wrote creates copies every single frame while we’re holding down the fire button. We need to change GetButton(“Fire”) into GetButtonDown(“Fire”), so it only shoots at the first frame after
we’ve pressed down the button, and not every frame. To give the freshly shot arrow velocity, first, we need to make a variable to store it temporally. Let’s declare one, name it
arrow and make it equal to the Instantiate part of the code. Before we can give it velocity,
the arrow needs to have a Rigidbody2D component, which gives the arrow physics behavior. Let’s
go back to the Unity Editor and select the arrow Prefab. Hitting Add Component in the
Inspector window, we can see all the available components we can add to our Prefab. Let’s
search for Rigidbody2D and add it to it. Now, we can go back to the script editor, and make
our arrows move. All arrows now have a Rigidbody2D component. This component has a variable,
called velocity which is a 2D vector with the movement direction in it. We can access
the current arrow GameObject’s Rigidbody2D component by typing arrow.GetComponent(). This GetComponent() function will give us back the Rigidbody2D component, so we can
refer to its velocity variable by typing .velocity to the end. Changing the velocity variable’s
value to a new Vector2(1.0f, 0.0f), we make the arrow move horizontally to the right.
Let’s try it out! Oh no, our arrow dropped like a stone. We have to get rid of the gravity
to let our arrows fly smoothly. Let’s select the arrow Prefab again, and in the Rigidbody2D
component, we need to change Gravity Scale to 0. If we test it now, then the arrows move
smoothly to the right. But its a bit slow, so let’s crank up the velocity a bit! Let’s
change the first value of the Vector2 to 5.0f. That’s much better! That’s it for today folks! Next
Wednesday, we will continue with part 2 of Shooting Arrows. We will fire arrows in any
direction and rotate them to match that direction as well. So be sure to subscribe and leave
a thumbs up! If you have any questions from today, feel free to ask and I’ll try to answer
all of them. See you next time!

13 thoughts on “Unity Shooting Arrows in Top Down Perspective Part 1 – Tutorial

  1. Nice video as always. Just a question. How would you approach the code if you want the character to rotate towards the mouse position, and also change sprite depending on which direction you're pointing the mouse? Example: The mouse is pointing to the right, so it should render the sprite for (moving right), even if I'm walking to the left it should follow the mouse.

  2. yohhh!! i'm spaming the arrows without pressing the key :C
    btw i'm doing this in a 2d platformer

    EDIT: nvm it was a '';'' in the if statement ///// if (Input.GetKey(KeyCode.K)) ; <—

    anyway keep the good work <3 love u <3

    here's the code:

    using System.Collections;

    using System.Collections.Generic;

    using UnityEngine;

    public class Bow : MonoBehaviour

    {

    public GameObject arrowPrefab;

    // Start is called before the first frame update

    void Start()

    {

    }

    // Update is called once per frame

    void Update()

    {

    if (Input.GetKey(KeyCode.K)) ;

    {

    GameObject arrow = Instantiate(arrowPrefab, transform.position, Quaternion.identity);

    arrow.GetComponent<Rigidbody2D>().velocity = new Vector2(5.0f, 0.0f);

    }

    }

    }

    AND HERE IS MY PLAYER CONTROLLER:
    using System.Collections;

    using System.Collections.Generic;

    using UnityEngine;

    public class PlayerController : MonoBehaviour

    {

    public float speed;

    public float jumpForce;

    private float moveInput;

    private Rigidbody2D rb;

    private bool facingRight = true;

    private bool isGrounded;

    public Transform groundCheck;

    public float checkRadius;

    public LayerMask whatIsGround;

    public int extraJumps;

    public int extraJumpsValue;

    //

    //

    void Start()

    {

    extraJumps = extraJumpsValue;

    rb = GetComponent<Rigidbody2D>();

    }

    void FixedUpdate()

    {

    isGrounded = Physics2D.OverlapCircle(groundCheck.position, checkRadius, whatIsGround);

    moveInput = Input.GetAxis("Horizontal");

    rb.velocity = new Vector2(moveInput * speed, rb.velocity.y);

    if (facingRight == false && moveInput > 0)

    {

    Flip();

    }

    else if (facingRight == true && moveInput < 0)

    {

    Flip();

    }

    }

    void Update()

    {

    if (isGrounded == true)

    {

    extraJumps = extraJumpsValue;

    }

    if (Input.GetKeyDown(KeyCode.W) && extraJumps > 0)

    {

    rb.velocity = Vector2.up * jumpForce;

    extraJumps–;

    }

    else if (Input.GetKeyDown(KeyCode.W) && extraJumps == 0 && isGrounded == true)

    {

    rb.velocity = Vector2.up * jumpForce;

    }

    }

    void Flip()

    {

    facingRight = !facingRight;

    transform.Rotate(0f, 180f, 0f);

    }

    }

  3. When i create Gameobject arrow equal to instantiate . Get error cant cannot implicitly convert type object to Gameobject ??

  4. Hey everyone! 👏 👏
    I'm happy to announce our community Discord server , come and join us : https://discord.gg/dac7sr2
    And also, you can get all the Sprites and Project Files by supporting me on Patreon : https://www.patreon.com/CouchFerret

  5. Your videos are one of the best Unity tutorials. It's better than most of the tutorials on their official site. Really hope you can make more videos, you should get huge popularity if you have more videos.

Leave a Reply

Your email address will not be published. Required fields are marked *