Shooting in 45 degrees – 2d shooter game

Updated on October 30, 2017 in [A] 2D
Share on Facebook0Tweet about this on TwitterShare on Google+0Share on Reddit0
3 on October 26, 2017

Hi guys

I’m stuck on something that maybe is a really easy thing to do, but my knowledge is limited

I want that my character shoots in 45 degrees angles when I press the direction key + up key

This is a new feature that I wanted to implement to my test game, so by now I have this code:

using UnityEngine;
using System.Collections;
public class BasicWeapon : MonoBehaviour {
 public GameObject projectile;
 public string shootKey;
 public Vector2 speed;
 bool canShoot= true;
 public Vector2 offset = new Vector2(4f,0.1f);
 public float cooldown = 1f;
 public GameObject playerDir;
 //trying to flip sprite
// Use this for initialization
 void Start () {
 // get a reference to the SpriteRenderer component on this gameObject
// GameObject g = GameObject.Find("Player Two");
 // Update is called once per frame
 void Update () {
 if (Input.GetKeyDown (shootKey) && canShoot){
 if (playerDir.transform.localScale.x < 0 && projectile.transform.localScale.x > 0) {
 Debug.Log ("left");
 projectile.transform.localScale *= -1;
 } if (playerDir.transform.localScale.x > 0 && projectile.transform.localScale.x < 0) {
 Debug.Log ("right");
 projectile.transform.localScale *= -1;
 GameObject go = (GameObject) Instantiate (projectile, (Vector2)transform.position + offset * transform.localScale.x, Quaternion.identity);
 go.GetComponent<Rigidbody2D> ().velocity = new Vector2 (speed.x * transform.localScale.x, speed.y);
 StartCoroutine (CanShoot ());
 IEnumerator CanShoot()
 canShoot = false;
 yield return new WaitForSeconds (cooldown);
 canShoot = true;


But this depends on the direction of the player only. What should I use to get a different angle for the proyectile?

I was trying to use Quaternion.AngleAxis with no sucess.


Any help will be appreciated.

Sorry if it is a dumb question, I’m really new to this.



  • Liked by