Advertisement

implementing events

Started by July 02, 2018 03:03 AM
2 comments, last by Martin Brentnall 6 years, 2 months ago

I'm trying to let one of my classes know when something collides with something else and I think it would be a really good opportunity to learn how to implement events. Basically, I've got a bunch of balls on the screen and if any of them hit anything, I need one of my classes to be notified and to call a method when this happens. How can I implement this? I've looked at this here:

https://stackoverflow.com/questions/1249517/super-simple-example-of-c-sharp-observer-observable-with-delegates

But I don't really understand what exactly is going on or how to tie this into my own code. For reference, the class that needs to be notified of the collision is AssaultRiflePickUp, and the class that we are watching for is Ball. Thanks for the help!

I'm still trying to figure this out. I thought I had found a good tutorial to show me how to set it up, and it would be if it was as simple as that example, but I've discovered a problem that may change what I need to do here. As I said in the original post, I had thought the AssaultRiflePickUp class would be the subscriber and the Ball class would be the Observable class. However, since the balls will spawn throughout the game, I'm not so sure this is the best route to take since I can't seem to figure out how to set up the code so that the AssaultRiflePickUp will subscribe to the ball's as they instantiate. Unless I am understanding this wrong. To explain exactly what I am trying to do, I have balls that will spawn in quick succession and all follow the same vector, as each one makes impact with something, I want it to be destroyed unless it is the last ball. My plan was to let the AssaultRiflePickUp know when a ball has hit something, check if there is more than one ball, and if so, destroy it. Does anyone know how I can accomplish this? With or without events. Thank you.

Advertisement

The way I did this was to register all of the fixed (non-moving) objects like walls and pick-ups into a "FixedObjects" collection class, then each time my moving object moves, it calls a "FixedObjects.testCollisions(this, startLocation, endLocation)", which iterates through all the fixed objects to test if the moving object collided with any of them.  Then when a collision tests positive, an action method is called with the fixed object and moving object as the two arguments.

That's actually a very simplified description compared to what I really did, but I hope it gives some idea of how to get started.

I didn't try collisions between two moving objects yet, so hopefully someone else can chime in if you need to do that.

 

This topic is closed to new replies.

Advertisement