Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by theoyoshimura · Jan 21, 2021 at 05:10 PM · unity 2deuleranglestopdowntop down shooterobjectpool

Need some help calculating Euler Angles

Hello! So I'm trying to make a top down shooter controller that uses object pooling for the bullet prefabs, some of the scripts are from this tutorial:

https://www.youtube.com/watch?v=Mq2zYk5tW_E&t=114s

I'm failing to make the calculations of the Euler Angles correctly, the PlayerBulletPoolAttack function is the one that I need to make some change. I need it to calculate the startAngle and endAngle relative to the players mouse position, how can I do that??

I'm using these scripts:

BulletPoolScript

public class BulletPool : MonoBehaviour { public static BulletPool bulletPoolInstance;

 [SerializeField]
 public GameObject pooledBullet;
 private bool notEnoughBulletsInPool = true;

 private List<GameObject> bullets;

 private void Awake()
 {
     bulletPoolInstance = this;
 }

 void Start()
 {
     bullets = new List<GameObject>();
 }

 public GameObject GetBullet()
 {
     if(bullets.Count > 0)
     {
         for(int i = 0; i < bullets.Count; i++)
         {
             if (!bullets[i].activeInHierarchy)
             {
                 return bullets[i];
             }
         }
     }

     if (notEnoughBulletsInPool)
     {
         GameObject bul = Instantiate(pooledBullet);
         bul.SetActive(false);
         bullets.Add(bul);
         return bul;
     }

     return null;
 }

}

PlayerBulletScript

public class DefaultPlayerProjectile : MonoBehaviour { private Vector2 moveDirection; public float moveSpeed = 200f;

 private Rigidbody2D rb2D;

 private void Start()
 {
     rb2D = GetComponent<Rigidbody2D>();
 }

 private void FixedUpdate()
 {
     rb2D.velocity = moveDirection * moveSpeed * Time.deltaTime;
 }

 public void SetMoveDirection(Vector2 dir)
 {
     moveDirection = dir;
 }

 private void DestroyPoolObject()
 {
     gameObject.SetActive(false);
 }

 private void OnTriggerEnter2D(Collider2D other)
 {
     if (other.CompareTag("Enemy"))
     {
     Debug.log("Enemy Hit!");
     }

     DestroyPoolObject();
 }

}

PlayerAttackFunction

[SerializeField] private int bulletsAmount = 10;

 [SerializeField]
 private float startAngle = 0f, endAngle = 0f, centerAngle = 0f;

 private Vector2 bulletMoveDirection;


 private void Awake()
 {
     instance = this;
 }
 private void Update()
 {
     centerAngle = (PlayerAimController.instance.weaponRotation.eulerAngles.z);
 }

 public void PlayerBulletPoolAttack(Transform firePoint)
 {
     float angleStep = (endAngle - startAngle) / bulletsAmount;

     float angle = startAngle;

     for (int i = 0; i < bulletsAmount + 1; i++)
     {
         float bulDirX = transform.position.x + Mathf.Sin((angle * Mathf.PI) / 180f);
         float bulDirY = transform.position.y + Mathf.Cos((angle * Mathf.PI) / 180f);

         Vector3 bulMoveVector = new Vector3(bulDirX, bulDirY, 0f);
         Vector2 bulDirection = (bulMoveVector - transform.position).normalized;

         GameObject bul = BulletPool.bulletPoolInstance.GetBullet();
         bul.transform.position = firePoint.position;
         bul.transform.rotation = firePoint.rotation;
         bul.SetActive(true);
         bul.GetComponent<DefaultPlayerProjectile>().SetMoveDirection(bulDirection);

         angle += angleStep;


     }
 }

PlayerAimController

public class PlayerAimController : MonoBehaviour { public static PlayerAimController instance; public bool isFlipped; private Camera mainCamera; public Transform weaponRotationPoint;

 private void Awake()
 {
     instance = this;
 }

 private void Start()
 {
     mainCamera = Camera.main;
 }

 private void Update()
 {
     GetPlayerAimInput();
 }

 void GetPlayerAimInput()
 {
     Vector3 mousePos = Input.mousePosition;
     Vector3 screenPoint = mainCamera.WorldToScreenPoint(transform.localPosition);


     //ROTATING THE PLAYER
     if (mousePos.x < screenPoint.x)
     {
         transform.localScale = new Vector3(-1f, 1f, 1f);
         weaponRotationPoint.localScale = new Vector3(-1f, -1f, 1f);
         isFlipped = true;
     }
     else
     {
         transform.localScale = Vector3.one; // transform.localScale = new Vector3(1f, 1f, 1f);
         weaponRotationPoint.localScale = Vector3.one;
         isFlipped = false;
     }

     //ROTATING THE GUN
     Vector2 offset = new Vector2(mousePos.x - screenPoint.x, mousePos.y - screenPoint.y);
     //RETURNS ANGLE BETWEEN X AND Y
     float angle = Mathf.Atan2(offset.y, offset.x) * Mathf.Rad2Deg;
     weaponRotationPoint.rotation = Quaternion.Euler(0, 0, angle);
 }

}

ShootingFunction

public void ProjectileShot() { PlayerRangedAttack.instance.PlayerBulletPoolAttack(shotPoint); }

I tried creating a variable to store the player's weapon rotation(centerAngle). But when I try to apply that to the PlayerAttack function the angles are always weird, I need some help finding the correct formula to calculate this. Can please someone help? Thank you so much for reading this.

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

1 Reply

· Add your reply
  • Sort: 
avatar image
2

Answer by jackmw94 · Jan 22, 2021 at 10:10 AM

There are 2 methods to do this:

First, the maths way:
Step 1: Get the vector from the ship to mouse position
Step 2: Find the angle of that vector from 0 degrees or "Vector2.Up"
Step 3: Rotate each direction by this angle

 // before your for loop:
 
 Vector2 aimVector = Input.mousePosition - transform.position;
 float aimAngle = Vector2.Angle(Vector2.up, aimVector);
 
 // then before you use bullet direction:
 
 Vector2 adjustedBulDirection = Quaternion.AngleAxis(aimAngle, Vector3.forward) * bulDirection;


Quaternions might be quite scary but as long as your use their functions as they describe them and worry less about what's going on under the hood, they're great! That mantra has served me for years of game dev, it's not just advice for while you're learning! What they're doing here is rotating the vector around the forward direction, which in your 2D game is the vector going into the screen. You could also google a 2D vector rotation function and use that instead, imo unity should provide that.

However, the easiest way is probably using unity's transforms to do it for you:

 Transform weaponRotation = PlayerAimController.instance.weaponRotation;
 Vector2 adjustedBulDirection = weaponRotation .TransformDirection(bulDirection);


What this does is it takes your direction in world space and makes it relative to the transform, what was previously a global forward now points in the forward direction of the transform.

Let me know if you run into any issues!

Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image theoyoshimura · Jan 24, 2021 at 03:16 AM 0
Share

$$anonymous$$y god thank you so much it worked perfectly with your code! I'm gonna do some more research on Vector2 Rotation. Thanks again! Have a wonderful day.

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

119 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

2D Top Down Shooting Problem 1 Answer

Unity 2D Collider did not create any collision shapes as they all failed verification 0 Answers

2d Top Down Shooter Jerky Movement 0 Answers

How to create a field of view for enemy ai that detects a player Unity 2d? 3 Answers

I need to make the direction.x negative without the direction.y being negative any help?,Hi so i need to change the direction.x to negative without the direction.y being negative could anyone know how? 0 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges