Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 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 /
  • Help Room /
This post has been wikified, any user with enough reputation can edit it.
avatar image
0
Question by DaBuilda · Dec 20, 2019 at 01:51 PM · 2d gamepoolingupdating

Bullet not going in the direction which it is facing.

I am working on a 2D game in which the player rotates around its own axis in space, and when the player shoots a bullet, he moves in the opposite direction of the shot bullet. (This is just the player movement part).

Problem: I have created an object pool from which I draw the bullets that I have to shoot, but sometimes the bullets do not go in the direction they are supposed to go. They spawn facing the correct direction and move in some other direction. And if I do not use the object pool, this problem goes away (but I do want to use the object pool).

Here are the codes:

Bullet Code -

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 
 public class Projectile : MonoBehaviour {
     public float speed = 5f;
     public float mag = 1f;
     public GameObject bulletBottom;
     public float outbound = 0f;
     private Rigidbody2D bullet;
     public Rigidbody2D player;
     public float playerSpeed = 5f;
     private float dirx = 0;
     private float diry = 0;
     private bool oneTime = false;
     private Vector3 bottomLeftScreenPoint;
     private Vector3 topRightScreenPoint;
     public Vector2 screenBounds;
     private ObjectPooler objPooler;
 
     void Start () {
         oneTime = false;
         objPooler = ObjectPooler.Instance;
         screenBounds = Camera.main.ScreenToWorldPoint(new Vector3(Screen.width, Screen.height, Camera.main.transform.position.z));
         bottomLeftScreenPoint = Camera.main.ScreenToWorldPoint(new Vector3(0f, 0f, Camera.main.transform.position.z));
         topRightScreenPoint = Camera.main.ScreenToWorldPoint(new Vector3(Screen.width, Screen.height, Camera.main.transform.position.z));
   
         player = GameObject.FindGameObjectWithTag("Player").GetComponent<Rigidbody2D>();
         bullet = GetComponent<Rigidbody2D>();
     }
 
     private void OnEnable()
     {
         GetComponent<Rigidbody2D>().velocity = new Vector2(0, 0);
         oneTime = false;
     }
 
     void FixedUpdate () {
         if (!oneTime)
             RecoilandShoot();
 
         if ( transform.position.y < bottomLeftScreenPoint.y - outbound  || transform.position.y > topRightScreenPoint.y + outbound || transform.position.x < bottomLeftScreenPoint.x - outbound || transform.position.x > topRightScreenPoint.x + outbound)
         {
             //Destroy(gameObject);
             bullet.velocity = new Vector2(0, 0);
             gameObject.SetActive(false);
             objPooler.poolDictionary["Bullet"].Enqueue(gameObject);
         }
     }
 
     void RecoilandShoot() {
         dirx = (transform.position.x - bulletBottom.transform.position.x) * mag;
         diry = (transform.position.y - bulletBottom.transform.position.y) * mag;
 
         bullet.velocity = new Vector2(0, 0);
         bullet.AddForce(new Vector2(dirx * speed * Time.deltaTime, diry * speed * Time.deltaTime), ForceMode2D.Impulse);
         player.velocity = new Vector2(0, 0);
         player.AddForce(new Vector2(-(dirx * playerSpeed * Time.deltaTime), -(diry * playerSpeed * Time.deltaTime)), ForceMode2D.Impulse);
         oneTime = true;
     }
 
     private void OnTriggerEnter2D(Collider2D other)
     {
         if(other.CompareTag("Enemy"))
         {
             //Destroy(gameObject);
             bullet.velocity = new Vector2(0, 0);
             gameObject.SetActive(false);
             objPooler.poolDictionary["Bullet"].Enqueue(gameObject);
         }
     }
 }


Object Pooler Code -

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 
 public class ObjectPooler : MonoBehaviour
 {
     [System.Serializable]
     public class Pool
     {
         public string tag;
         public GameObject prefab;
         public int size;
     }
 
     public List<Pool> pools;
     public Dictionary<string, Queue<GameObject>> poolDictionary;
     private Dictionary<string, GameObject> prefabDictionary;
 
     #region Singleton
     public static ObjectPooler Instance { get; private set; }
 
     private void Awake()
     {
         Instance = this;
         CreatePoolDict();
     }
     #endregion
 
     //create pool dictionary
     void CreatePoolDict()
     {
         poolDictionary = new Dictionary<string, Queue<GameObject>>();
         prefabDictionary = new Dictionary<string, GameObject>();
 
         foreach(Pool pool in pools)
         {
             Queue<GameObject> objectPool = new Queue<GameObject>();
 
             for(int i = 0; i < pool.size; i++)
             {
                 GameObject obj = Instantiate(pool.prefab);
                 obj.SetActive(false);
                 objectPool.Enqueue(obj);
             }
 
             poolDictionary.Add(pool.tag, objectPool);
             prefabDictionary.Add(pool.tag, pool.prefab);
         }
     }
 
     public GameObject spawnFromPool(string tag, Vector2 position, Quaternion rotation)
     {
         if (!poolDictionary.ContainsKey(tag))
         {
             return null;
         }
         //if one of the pools is empty
         if(poolDictionary[tag].Count == 0)
         {
             AddObjectsToPool(tag, 1);    
         }
 
         GameObject objectToSpawn = poolDictionary[tag].Dequeue();
 
         objectToSpawn.SetActive(true);
         objectToSpawn.transform.position = position;
         objectToSpawn.transform.rotation = rotation;
 
         return objectToSpawn;
     }
 
     private void AddObjectsToPool(string tag, int num)
     {
         GameObject prefabToAdd = null;
         //get prefab
         prefabToAdd = prefabDictionary[tag];
         //adding objects to pool
         for(int i = 0; i < num; i++)
         {
             GameObject obj = Instantiate(prefabToAdd);
             obj.SetActive(false);
             poolDictionary[tag].Enqueue(obj);
         }
     }
 }
 

Thanks in advance :)

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

0 Replies

· Add your reply
  • Sort: 

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

189 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 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

Can someone post a generic object pool script? 4 Answers

How can I fix my object pool to continue after original pool is exhausted? 0 Answers

text not changing in build for android unity 1 Answer

Pickup weapons in 2D scroller game 1 Answer

Touchscreen Start Button 2 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