# Algorithm examples of how pickups are handled

## Recommended Posts

I'm wondering if anyone has any examples or tips/ideas on how to handle pickups in a game. The game is an arkanoid style game. I'm going to have at least 5 different pick up types, and they are going to be in a queue, where only one can be active at a time. Once one pick up is expended, the next one should automatically start up. Some of the pick ups have an immediate effect, such as ball speed. Others will activate when the pickup is hit, but doesn't actually do anything until the ball hits the paddle. Those type of pick ups have a limited number of shots instead of a time limit. What I'm trying to figure out is what kind of structure I should have for a system like this? I'm just curious how these things are handled in other games, especially if anyone has any examples that would be great. Thank you!

##### Share on other sites
Posted (edited)

My guess would be that most games add pickup stats in their "getStatusXY()" function which then calls something like "getPickupBonus()" which loops through all pickups and calculates the bonus for this specific situation and status and returns a flat number or percentage to add to the actual status value.

Pick out 10 different games and they will all do it a different way.

You have to find a way for your specific case.

I would suggest you to make a myPickups array and save your aquired pickups in there.

Then whenever you call your getStatXY() function (e.g. getSpeed()) you add a function in there to check for pickups.

This checkForPickups() function then should loop through all pickups and add all stat changes.

Then you can be sure to always get the correct stat and won't miss any line in code where the stat might be without the pickup.

You could then add a parameter like "withoutPickups = false" which can be set to true and then only returns the stat without the pickup.

For example:

16 hours ago, ethancodes said:

Some of the pick ups have an immediate effect, such as ball speed.

When you get the pickup, you add it to the myPickups array. Then you get the speed from function getSpeed() which checks the myPickup array for speed modifying pickups. This way you don't have to worry about pickups when you just want to have the current speed.

16 hours ago, ethancodes said:

Others will activate when the pickup is hit,﻿ but doesn't actually do anything until the ball hits the paddle.﻿

When you hit the pickup, you add it to the myPickups array. When hitting the paddle you check the myPickups array if this pickup is in there.

This way you could have more than one pickup at the same time. Of course you can also change the myPickups array to one Pickup called activePickup which is referring to the currently active pickup. When the time for this pickup is up, you change activePickup to the next pickup.

If that is not possible for you, you might want to give some code examples or a more detailed explanation on your pickup code.

Edited by SeelenGeier

##### Share on other sites

This gives me some ideas and I'm slowly starting to piece this whole thing together. I'm considering using the observer pattern by having a PickUpManager that listens to each of the pick ups. When the pick up gets collected, it destroys itself and sends the info to it's listeners, in this case it would most likely be just the PickUpManager. The PickUpManager will then know which PickUp was destroyed, and can create an instance of that PickUp in it's List<BasePickUp>. When it adds a pickup to the list, it sets a bool hasPickUp to true. Update function will check that bool every frame. If it is false, the game just continues, if it is true, it checks the first item in the list, finds out what kind of pickup it is, and calls a method based on that pick up to activate it. If it is a fast ball pickup, the ball goes faster for a limited time, then goes back to normal speed after the timed coroutine is finished. At this point, the object in the list is destroyed and the next in line steps up, if there is one. If there isn't one, we set hasPickUp to false and the game continues. Where I'm having a hard time is with the multishot pickups. The object in the list could hold information on how many shots there are. But is there a way for me to check if the ball hit the paddle from the PickUpManager? Can I do something that translates to "If multishot pick up is active, watch for ball collision with paddle"? If so, how would I do that? I think if I can figure out this part, I can finally piece this thing together and have a pretty solid base to build off of.

##### Share on other sites

Then I would suggest you use PickupList.count() instead of a flag that you set and unset manually.

I don't know how your code is structured so I can't give a specific advice for the collision.

I would try to implement an event list where you can register callbacks.

Something like this:

When the player receives the pickup, you set an event called onPaddleHit which calls the multishot function.

every time the ball hits the paddle, you check if this event has been registered and then fire the multishot function if it is.

##### Share on other sites

I'm trying to figure out the Observer pattern. I haven't used it before but most examples look pretty straight forward. However, some parts of my setup are making it a bit more difficult. I believe I've got the observable item set up correctly, that would be on the BasePickUp class, that way all pick ups that implement that are observable. That is this code here:

public event EventHandler PickUpCollected; //Event to raise if pick up is collected

protected void OnPickUpCollected (EventArgs e) //Notify observers if event is raised
{
if (PickUpCollected != null)
{
PickUpCollected(this, e);
}
}

And I believe what I'm wanting to do is to set up the observer part on the PickUpManager, so that it is notified any time a PickUp is collected. The things I'm not sure about are:

1. The basic structure of the observer, since the pickups will be spawned and are not something that is just hard coded to be subscribed to.

2. how to let the PickUpManager know which pickup was collected so that it may react accordingly.

I found this site here: https://www.codeproject.com/Articles/1084848/Implementing-Observer-Pattern-with-Events-Csharp and it does a pretty good idea of explaining the simple version, but I'm still very confused.

##### Share on other sites
Posted (edited)
54 minutes ago, ethancodes said:

I found this site here: https://www.codeproject.com/Articles/1084848/Implementing-Observer-Pattern-with-Events-Csharp and it does a pretty good idea of explaining the simple version, but I'm still very confused.

It is an event with a trigger. For example:

Say there is a soccer ball in the middle of the scene. There is a player and a AI. We want the AI to chase the player when he has the ball.

So we make the players collision function a Event. Both the player and the AI are observers of this event. So now if the player collides with the ball we can parent the ball to the player, and the AI is also told the player has the ball, allowing the AI to start chasing the player.

Think of it has having a IF function that checks to see if that event happened.

On 6/5/2018 at 10:43 PM, ethancodes said:

I'm wondering if anyone has any examples or tips/ideas on how to handle pickups in a game.

Using a Observer pattern gives you more flexibility but isn't needed for powerups.

You could also just make a powerup class with it's own execute function that applies the effect to the player it collides with.

Edited by Scouting Ninja

##### Share on other sites

I'm not sure what you mean exactly by that last line. "applies the effect to the player it collides with."  I created a PickUpManager and I'm planning on have it track the pick ups in the queue, as well as apply all effects the pick ups do. So the pick ups themselves will basically just be a ball bouncing around until it hits the main ball or the paddle, in which case an instance of the pick up gets added to a list. The update function on the PickUpManager will then find that and activate it accordingly.

I'm trying to figure out how to let hte PickUpManager know about the collision between the pickup and ball or paddle. It needs to know that the collision happened and what type of pick up it was. I thought the observer pattern would be a good way to do this, but I'm open to different options.

##### Share on other sites
10 minutes ago, ethancodes said:

So the pick ups themselves will basically just be a ball bouncing around until it hits the main ball or the paddle, in which case an instance of the pick up gets added to a list.

This ball needs some way to collide and to know what it collided with. This means adding collisions to it; just use the Unity 2D collisions. When the two collides you can let the ball implement the code to the object it collided with.

The code would look something like this:

using UnityEngine;
using System.Collections;

public class DoubleSpeed : MonoBehaviour
{
void OnCollisionEnter (Collision col)
{
if(col.gameObject.name == "Player1")
{
col.gameObject.velcoity*2f;//double speed
Destroy(self.gameObject);//Destroy powerup
}
}
}

Any variable your player has that is public can be used this way. The Collision system in Unity follows the Observer pattern.

##### Share on other sites

This was initially how I had the simpler pick ups set up. However, the other pick ups I'm working on do things like "when the main ball comes back and hits the paddle, if a spread shot pick up is active, shoot several balls out from the paddle. And this will be active for a certain number of shots. So I need a way to manage this, as well as managing those extra balls because all the balls will be destroyed on impact (except the last one). Also, my pick ups line up in a queue. So if I have a fast ball active but then I grab a spread shot, I don't want fast ball and spread shot both active. Spread shot would be on stand by in the queue.

##### Share on other sites
Posted (edited)
9 minutes ago, ethancodes said:

Also, my pick ups line up in a queue﻿.

Still very similar. Just make a pickup class then make a public queue:

using UnityEngine;
using System.Collections;

public class DoubleSpeed : MonoBehaviour
{
void OnCollisionEnter (Collision col)
{
if(col.gameObject.name == "Player1")
{
Destroy(self.gameObject);//Destroy powerup
}
}
}

Then in your player class you need some way to execute power ups.

Edited by Scouting Ninja

## Create an account

Register a new account

• ### Similar Content

• Been a bit quiet recently, but we've been busy bug fixing and tweaking things... Now we have lots more 'Particle effects' in the game, specifically here the Flamethrower and Enemy attacks!

• Hello Guys!
Please share your experience, where is it better to find sales manager  specialists for indie team of 6 + people(remotely)?
Maybe someone has a good experience of cooperation with finding projects through sale managers(USA and Canada)?

In our team more than 6 developers. We are working since 2014 now we are looking for projects mainly on upWork and Unity Connect.
But that's not enough
This is the site of our team https://www.sixteensq.com/
https://www.behance.net/Dezignw136f
Thank you
Best Regards
Alex Vovk
Co-Founder of Sixteen Squares
Alexander_Vovk@outlook.com

• Hi and thanks for reading, I have an issue with this reactive crosshair script, everything works fine until I start changing the offset. Give the script a go and you will see what I mean, when I do SetOffset(0f); it doesnt always set back to the origional state, if anyone can spot a fix I'd be super appreciative!
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ReactiveCrosshair : MonoBehaviour { [SerializeField] GameObject c_limb_prefab; private float center_offset = 0f; private float current_offset = 0f; private float max_offset = .5f; private int number_of_limbs = 4; private float limb_length = .05f; private float limb_width = .005f; private List<GameObject> c_limbs = new List<GameObject>(); public void SetupCrosshair(){ for (int i = 0; i < number_of_limbs; i++) { GameObject line_go = (GameObject)Instantiate (c_limb_prefab); line_go.transform.SetParent (this.transform); Vector3 limb_pos = new Vector3 (0f,0f,0f); //line_go.transform.position = limb_pos; line_go.transform.localPosition = limb_pos; LineRenderer line = line_go.GetComponent<LineRenderer>(); line.startWidth = limb_width; line.positionCount = 2; line.SetPosition (0, line_go.transform.localPosition + new Vector3(center_offset, 0f, 0f)); line.SetPosition (1, line_go.transform.localPosition + new Vector3(center_offset + limb_length, 0f, 0f)); line.useWorldSpace = false; c_limbs.Add(line_go.gameObject); } if (c_limbs != null) { OrientLimbs (); SetOffset (0f); } } public void OrientLimbs(){ for (int i = 0; i < c_limbs.Count; i++) { float rotation_step = 360f / (float)c_limbs.Count; c_limbs [i].transform.RotateAround (c_limbs[i].transform.position, c_limbs[i].transform.forward, 90f + (rotation_step * (float)i)); } } public void SetOffset(float _current_spread){ float offset = Mathf.Lerp (0f, max_offset, _current_spread); for (int i = 0; i < number_of_limbs; i++) { if (offset > current_offset) { Vector3 pos = c_limbs [i].transform.position + (c_limbs [i].transform.TransformDirection (Vector3.right) * offset); c_limbs [i].transform.position = pos; } if (offset < current_offset) { Vector3 pos = c_limbs [i].transform.position - (c_limbs [i].transform.TransformDirection (Vector3.right) * offset); c_limbs [i].transform.position = pos; } } Debug.Log ("SetOffset() offset: " + offset.ToString () + " _current_spread: " + _current_spread.ToString() + " localPos: " + c_limbs[1].transform.localPosition); current_offset = offset; } }

• So, as the title says i am trying to figure out a good way sync all that information with other players in Unity. My problem is that i can't come up with a good solution since i am used to creating classes for everything e.g. attachments are its own class and then the weapon would save a reference to that attachment. But since you can't send custom classes over [Command] & [ClientRPC] i am a little stuck. A solution for this would be giving each attachment for a slot a unique ID and then passing the ID to other player but i feel like that is very error prone if other ppl add a new attachment or the IDs get mixed up.
Is there a "standard" way that this is usually done that i am missing?
I am fairly new to programming so any help is appreciated!

• I'm looking for any team / people that need a programmer for their project. I'm looking to expand my portfolio which you can see Here. I'm more experienced with Unity but I can spend the time to learn new Engines if that's your preference. I have worked on Unreal Engine 4 before but I might take some time to re-learn it, if the project requires it. Feel free to DM here or use the contact info on my website.

• I'm working on a system for my game that will allow the player to stack pick ups in a queue. As one pick up expires, the next automatically activates. I'm having an issue though where if I pick up the first one, it activates fine, but if i pick up a second directly after it, it overrides the first one, activates the second one, and then once it has run it's course, everything goes back to normal gameplay, no first pick up. I'm not sure why this is happening. Hopefully someone can spot what I'm doing wrong in my code.
Here is the code for the pick up manager:
// Update is called once per frame void Update () { if (pickUpQueue.Count != 0 && !pickUpActive) { pickUpActive = true; pickUpQueue[0].ActivatePickUp(); } DeactivatePickUp(); } void DeactivatePickUp () { if (pickUpQueue.Count != 0 && pickUpActive) { Destroy (pickUpQueue [0]); pickUpQueue.RemoveAt (0); pickUpActive = false; } } And here is the PickUp:
public override void ActivatePickUp () { ball.GetComponent<Ball>().Speed = 2.0f; //increase ball speed... ball.GetComponent<Ball>().StartCoroutine(timer); //...set time that power up is active }
There is also a Base Pick Up:
public void OnCollisionEnter2D (Collision2D collision) { Vector2 tweak = new Vector2 (Random.Range(0f, 0.2f),Random.Range(0f, 0.2f)); this.gameObject.GetComponent<Rigidbody2D>().velocity += tweak; //if the pickup makes contact with the paddle or ball.... if (collision.gameObject.tag == "Paddle" || collision.gameObject.tag == "Ball") { GameObject.FindObjectOfType<GameManager>().GetComponent<PickUpManager>().pickUpQueue.Add(this); Destroy(gameObject); //...and finally destroy power up object } } As a side note, I am trying to find a solution to this that will work for all of my pickups. Some pickups are ammo based, some are timed.
• By D34DPOOL
Edit Your Profile D34DPOOL 0 Threads 0 Updates 0 Messages Network Mod DB GameFront Sign Out Add jobEdit jobDeleteC# Programmer for a Unity FPS at Anywhere   Programmers located Anywhere.
Posted by D34DPOOL on May 20th, 2018
Hello, my name is Mason, and I've been working on a Quake style arena shooter about destroying boxes on and off for about a year now. I have a proof of concept with all of the basic features, but as an artist with little programming skill I've reached the end of my abilities as a programmer haha. I need someone to help fix bugs, optomize code, and to implent new features into the game. As a programmer you will have creative freedom to suggest new features and modes to add into the game if you choose to, I'm usually very open to suggestions :).
What is required:
Skill using C#
Experience with Unity
Experience using UNET (since it is a multiplayer game), or the effort and ability to learn it
Compensation:
Since the game currently has no funding, we can split whatever revenue the game makes in the future. However if you would perfer I can create 2D and/or 3D assets for whatever you need in return for your time and work.
It's a very open and chill enviornment, where you'll have relative creative freedom. I hope you are interested in joining the team, and have a good day!

To apply email me at mangemason@yahoo.com

• Is there a way to automatically change the start position of an animation? I have a bunch of animations set up on 3D models in unity. The issue is that I need to move the 3D models, however when I do so the animation start positions are not updated and I have to do it manually.

Changing the transform of key frames is time consuming with the amount of animations I have, so I was wondering if there was a way to do it automatically?
• By MoreLion
hey all! We are looking for members for our Unity horror game!
Here’s the story:
After a deadly virus plunges the world into chaos killing 85% of the human population there are now what they call “zones” these zones are watched very closely by the surviving government, people are checked every day for the virus, even if you touch the spit or any human waste or fluids of the victim who is infected, you will die. But one day, people in the west zone start to go missing, 1 woman goes outside the walls to uncover the mystery, is there more to the virus than meets the eye?, That is where your story starts.
This game is not a long development game, I have loads other game ideas,
I will also allow you to have a bit of creative freedom if you wish to add or share a idea!
And no, it’s not a zombie game lol I feel like zombie games are too generic, in this game you will encounter terrifying beasts!
There is some concept art one of our concept artists have made
If interested email liondude12@gmail.com

• GOVERNOR is a modernized version of the highly popular series of “Caesar” games. Our small team has already developed maps, written specifications, acquired music and performed the historical research needed to create a good base for the programming part of the project.

Our ultimate goal is to create a world class multi-level strategic city building game, but to start with we would like to create some of the simpler modules to demonstrate proof of concept and graphical elegance.

We would like programmers and graphical artists to come onboard to (initially) create:

A module where Province wide infrastructure can be built on an interactive 3D map of one of the ancient Roman Provinces.
A module where city infrastructure can be built on a real 3D interactive landscape.
For both parts, geographically and historically accurate base maps will be prepared by our team cartographer. Graphics development will be using Blender. The game engine will be Unity.

More information, and examples of the work carried out so far can be found at http://playgovernor.com/ (most of the interesting content is under the Encyclopedia tab).

This project represents a good opportunity for upcoming programmers and 3D modeling artists to develop something for their portfolios in a relatively short time span, working closely with one of Canada’s leading cartographers. There is also the possibility of being involved in this project to the point of a finished game and commercial success! Above all, this is a fun project to work on.

Best regards,

• 16
• 11
• 10
• 9
• 49
• ### Forum Statistics

• Total Topics
631392
• Total Posts
2999742
×