XNA game frozen - xna

I was following a tutorial for creating a 2d space shooter. It was working fine until I added code to spawn enemy mobs, now it just runs but it's frozen. I can't understand why it wont work. there are no errors anywhere or anything like that.
Thanks.

You have a minor typo with the brackets in your update method.
protected override void Update(GameTime gameTime)
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
Exit();
//updating mobs and checking for collisions
foreach (Mobs M in mobsList)
{
// Updating the mobs, collision checking, etc here
...
...
Player.update(gameTime);
bG.update(gameTime);
loadAsteroids();
loadMobs();
foreach (Roids R in asteroidList)
{
// Updating the asteroids, collision checking, etc
...
...
M.update(gameTime);
R.update(gameTime);
}
base.Update(gameTime);
}
}
There are two main things wrong in this. Firstly, this bit of code:
Player.update(gameTime);
bG.update(gameTime);
loadAsteroids();
loadMobs();
foreach (Roids R in asteroidList)
{
// Updating the asteroids, collision checking, etc
...
M.update(gameTime);
R.update(gameTime);
}
base.Update(gameTime);
Will be run inside the first foreach loop. You are updating the player, the background, every asteroid, and the window once for each mob, every time you call update. This is only meant to happen once per update, not once per mob that is being updated. This is why your gaming is lagging or freezing. This is just a misplacement of the bracket on the mob's foreach loop - shift all this stuff outside the foreach loop.
The other thing wrong is this part:
foreach (Roids R in asteroidList)
{
// Updating the asteroids, collision checking, etc
...
M.update(gameTime); /* THIS LINE HERE */
R.update(gameTime);
}
Here, you are updating each Mob member once per asteroid. If you have 15 asteroids on screen, each mob member will be updated 15 times. Shift that line up into the first foreach loop.

Related

How do I delete a GameComponent from Game.Components?

Basically my game is to stop the rocks falling from the sky using a plank.
I'm not sure what is not functioning correctly, but here is my code:
In the RockManager class
public void CheckForPlankCollision(Plank plank)
{
foreach (GameComponent component in Game.Components)
{
if (component is FallingRock rock)
{
if (plank.Bounds.Intersects(rock.Bounds))
{
rock.HandleCollision();
Rectangle bounds = rock.Bounds;
}
}
}
}
In the Rocks class
public void HandleCollision()
{
//rockPosition = rockAfterImpactPosition; // I tried to move it offscreen
//rockPosition = Vector2.Zero; //I tried for any reaction
//this.Enabled = false; // tried this
//Game.Components.Remove(this); //tried this
}
I'm also trying to implement a scoring system. (add 1 point if the rock hits the plank, subtract a point if it hits the ground)
Try casting this as an IGameComponent or GameComponent object.
public void HandleCollision()
{
Game.Components.Remove((GameComponent)this);
}
Tell me if this works for you !
EDIT: You might also want to defer the deletion of your game object to later, when it isn't used by the foreach (GameComponent component in Game.Components) loop, which might have a lock on removing elements during that time.

Return/break out of infinite foreach in kotlin

For class I have to make a program that calculates the birthday problem
Now I'm having trying to learn kotlin at the same time and I'm having trouble with a little snippet of code:
val checkSet = mutableSetOf<Int>()
generateSequence{ Random.nextInt(n)}.forEach {
if(!checkSet.add(it)) {
return#outForeach
}
}
outForeach#
sum += checkSet.size
As you can see I'm trying to do this with an infinite sequence. Kotlin doesn't accept this as outForeach is an unresolved reference. But this doesn't work either:
val checkSet = mutableSetOf<Int>()
generateSequence{ Random.nextInt(n)}.forEach {
if(!checkSet.add(it)) {
return#forEach
}
}
sum += checkSet.size
This will just start the forEach loop again. Is there a way to implement something as a forEachUntil or so?
p.s. I'm aware that this looks a lot like this question: 'return' doesn't jump out of forEach in Kotlin It's just that I don't really get the answers and I don't know if its applicable here. Also a way to implement forEachUntil seems for me to be far more elegant
Alternatives you may want to consider instead of first:
using a simple while without body:
while (checkSet.add(Random.nextInt(n))); // <- that semicolon is required! otherwise you execute what is coming next within the while
using run with a label:
run outForeach#{
generateSequence{ Random.nextInt(n)}.forEach {
if(!checkSet.add(it)) {
return#outForeach
}
}
}
maybe also takeWhile might be helpful. In this specific case however it is surely not (as it would check against the checkSet and leave us with a sequence that isn't consumed... but if the condition would be different, it may make sense to consider something like take, takeWhile, takeLast, etc.):
generateSequence { Random.nextInt(n) }
.takeWhile(checkSet::add) // as said: for this specific condition it doesn't make sense...
.forEach { /* do nothing except consume the sequence */ } // the same values you added to the set would be available in this step of course
I think I found the solution myself:
val checkSet = mutableSetOf<Int>()
generateSequence{ Random.nextInt(n)}.first { !checkSet.add(it) }
sum += checkSet.size
Basically use the function first() and keep returning false until you want to get out of the loop. And just drop the return of the function first()

How to toggle a Key Press

I have the issue. I have programmed my Shoot em up and i came to dead end when i have to ask so many questions in here
if(key State.IsKeyDown(Keys.Space))
{
Shoot Bullets();
}
Problem is when i Hold Space bar it shoots....i do not want to hold Space bar for 30 minutes just to end the level. I wanna make it to toggle.
What is best and least coded way to do it.
I did spend like 2 days trying to figure this out and i can't...help would be appreciated
As #folkol suggested:
Include:
bool Shoot;
And initialize as:
Shoot = false;
What you check for input
if(key State.IsKeyDown(Keys.Space)) // Need to flip on key release
Shoot = !Shoot // Flips the variable
And in your Update() Method:
if(Shoot)
Shoot Bullets(); // Shoots
Notice that this will flip the Shoot Variable a lot. You will need to create an oldState value and flip on key release.
Instead of "Shoot Bullets", flip the value of a boolean variable. And use that variable as the indicated for whether you should fire some bullets in any given game loop iteration.
Something like this:
public class MyGame : Microsoft.Xna.Framework.Game
{
/* Some other state */
bool isShooting = false;
/* Some other methods */
protected override void Update(GameTime gameTime)
{
/* Some other code */
if(keyState.IsKeyDown(Keys.Space))
{
// Flip the boolean value. If it was failse, set it to and vice versa
isShooting = !isShooting; true.
}
if(isShooting)
{
Shoot.Bullets();
}
}
}
I added another short but correct example for you, some of the other answers were pretty much there, but had some errors in them.
KeyboardState kbState;
bool isShooting;
protected override void Update(GameTime gameTime)
{
KeyboardState lastkbState = kbState;
kbState = Keyboard.GetState();
if (kbState.IsKeyDown(Keys.Space) && lastkbState.IsKeyUp(Keys.Space))
{
isShooting = !isShooting;
}
if (isShooting)
{
Shoot.Bullets();
}
}
Your other answer I don't have the reptuation to add a comment on doesn't work because you made the previous and the current keyboard state properties equal the same thing.

The supplied DisplayObject must be a child of the caller

yes i know this question gets asked all the time, but my inexperience has prevented me from finding the answer. I'm simply trying to remove an object from the screen if a button is clicked -
public function but1click(evtObj:MouseEvent)
{
trace("button one clicked");
if (gracestate == "grace")
{
removeChild(grace);
trace("grace removed");
}
}
I traced the parent of the object (grace) and it came back as null. This is driving me nuts, and help would be much appreciated!
The question is unclear though the most likely problem seems to be you're storing a value into grace that is being garbage collected/deleted.
If you create a variable inside a function but no reference to that variable exists outside the function it will be GC'd. Basically anything that isn't referred to by something else is deleted, the only object this isn't true for is the timeline. This stops the flash player lagging and avoids errors when the RAM becomes full. Thus:
function createGrace () {
var grace = new Object();
addChild(grace);
}
trace (grace); // returns null
var grace:Object;
function createGrace () {
grace = new Object();
addChild(grace);
}
trace (grace); // returns [Object]

Inserting a delay between screen updates using Val and GTK3

I am learning Vala and GTK3 in a Linux (Ubuntu 12.04) environment. To do so, I have written a Game of Life simulation. So far so good. What I would like to do is insert a delay (say 2 seconds) between each screen update. I have investigated the Glib.TimeoutSource function and it seems over-elaborate for my needs. Are there other options? If TimeoutSource is indeed the way to go, are there any examples you might recommend.
Thank you.
Mike
Update: It turns out to be ridiculously easy ...
public void onRunButtonClicked(Button source)
{
Timeout.add_seconds(3, updateDraw);
}
private bool updateDraw()
{
game.determineBirthsAndDeaths();
game.applyBirthsAndDeaths();
queue_draw();
iterationsLabel.set_text("Iteration: %5d".printf(game.getIterationCount()));
return true;
}
The first method sets the timer. The second one executes every three seconds (in this example). Now I have to add a stop button and get my updateDraw method to return false when the stop button is pressed. More to learn ...
public void onRunButtonClicked(Button source)
{
Timeout.add_seconds(3, updateDraw);
}
private bool updateDraw()
{
game.determineBirthsAndDeaths();
game.applyBirthsAndDeaths();
queue_draw();
iterationsLabel.set_text("Iteration: %5d".printf(game.getIterationCount()));
return true;
}

Resources