Player does not stop when colliding with block [closed] - c#

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I'm trying to make it so my player comes to a complete halt when he hits a block, but can become unstuck if he presses a certain key(s). Example: Player is going down and hits a block. He stops, but if presses W, A, or D, he can move up, left, or right. Here's what I currently have for the code.
In this case, sp means speed, blocksp means his speed when he is being blocked. (This.Sprite), in this case, is referring to the block that stops him.
bool Blocked = false;
float Bottom = -32;
float Left = -32;
float Right = This.Sprite.GetWidth() - 32;
float Top = This.Sprite.GetHeight() - 32;
int x = 0;
int y = 0;
float sp = 1.59f;
float blocksp = 0.00f;
Sprite Player = This.Game.FindSprite("GuySprite");
if (This.Sprite.CollisionWithSprite("GuySprite") != null)
{
if (Player.Position.Y > Top)
{
Blocked = true;
Player.Velocity = new Point2D(x, y) * blocksp;
Player.Animation = 0;
if (This.Game.IsPressed(InputKey.W) || This.Game.IsPressed(InputKey.A) || This.Game.IsPressed(InputKey.D))
{
Blocked = false;
Player.Velocity = new Point2D(x, y) * sp;
Player.Position.Y -= 0.85f;
}
}
if (Player.Position.Y < Bottom)
{
Blocked = true;
Player.Velocity = new Point2D(x, y) * blocksp;
Player.Animation = 0;
if (This.Game.IsPressed(InputKey.S) || This.Game.IsPressed(InputKey.A) || This.Game.IsPressed(InputKey.D))
{
Blocked = false;
Player.Velocity = new Point2D(x, y) * sp;
Player.Position.Y += 0.85f;
}
}
if (Player.Position.Y < Right)
{
Blocked = true;
Player.Velocity = new Point2D(x, y) * blocksp;
Player.Animation = 0;
if (This.Game.IsPressed(InputKey.S) || This.Game.IsPressed(InputKey.A) || This.Game.IsPressed(InputKey.W))
{
Blocked = false;
Player.Velocity = new Point2D(x, y) * sp;
Player.Position.Y -= 0.85f;
}
}
if (Player.Position.Y > Left)
{
Blocked = true;
Player.Velocity = new Point2D(x, y) * blocksp;
Player.Animation = 0;
if (This.Game.IsPressed(InputKey.S) || This.Game.IsPressed(InputKey.W) || This.Game.IsPressed(InputKey.D))
{
Blocked = false;
Player.Velocity = new Point2D(x, y) * sp;
Player.Position.X += 0.85f;
}
}
}
Currently, if my player touches any side of the block and continues his movement that the block stops, the player will move in an erratic direction and does not stop at the block. Any ideas?

Edit
Ok
The player is running towards the block so he'll hit the left side in the next frames.
So that the following condition ll be true.
if (This.Sprite.CollisionWithSprite("GuySprite") != null)
Now you have to implement a method to find out which side the player collided with.
Actually your code is confusing me since:
Player.Velocity = new Point2D(x, y) * ...;
will always be the zero vector because x = y = 0
I'd do it like this :
float xDistance=0f, yDistance=0f;//this ll be explained later on
If(Player.Velocity.X > 0) //he is running to the right so he can hit the left side
xDistance=mayHitLeft();
Else If(Player.Velocity.X < 0)
xDistance=mayHitRight();
If(Player.Velocity.Y > 0) //In my case positive Y means downwards so can hit top
yDistance=mayHitTop();
Else If(Player.Velocity.Y < 0)
yDistance=mayHitBot();
Now we have to find out if the player hit the bot/top edge or the left/right edge or maybe both.
let's assume he is falling and was running to the right before.
so Player.Velocity.X > 0 and Player.Velocity.Y > 0
This means the function mayHitLeft(); and mayHitTop();
will be called.
I don't know how the collisionWithSprite function works.
But as always we take the worst case like this one blue is the block and orange the player.
This is the frame before hitting and no collision was detected by now. so in the next frame both functions would detect a collision but which is the right one. As we see it is colliding with the top. So how to detec the right one? Therefore we use the distance or let's say how much overlapping we have in which direction. So less overlap is the right one.
So both functions return a double. Let's look at the mayHitTop() function
private float mayhitTop()
{
//remember that the y coordinate goes downwards so we have to add
float playersBotCoordinate = Player.Position.Y + Player.Sprite.Height;
//the y position is the top so nothing to change
float blocksTopCoordinate = Block.Position.Y;
hitTop=true; //this is a global variable you have 1 for each direction
return Math.Abs(playersBotCoordinate - blocksTopCoordinate);
}
So we have set the xDistance and yDistance and we know that it will hit the top or left.
Now we have to compare everything
// this means there could be 2 sides like our case that can be ths possible collision edge
if((hitLeft || hitRight) && (hitTop || hitBot))
{
//we hit the left or right side
if(xDistance<yDisante)
{
Player.Velocity.X = 0;
}
//we hit top or bottom
else
{
Player.Velocity.Y=0;
}
}
else
{
if(hitLeft || hitRight)...
}
Maybe you have to unstuck the player. Otherwise I think there could be some problems.
So I just wrote it without any template. Don't know if there are any Syntax mistakes. but this shall only give you an overview how to do it ´we can expect this to be pseudocode ;)
Hope it'll help you at least a little.
Old
Ehhhh you are comparing the player position.Y with right and left
this should be the X coordinate if I understood the code ;)
if (Player.Position.Y < Right)
and
if (Player.Position.Y > Left)

Related

Why platformer collision works great on one platform, but barely works with platform array?

I have read all the suggested topics. I want to create collisions for platformer game with C#, .NET Gatgeteer, .NETMF 4.3 on VS 2013. I started with one platform and after some time collisions on it worked nicely. I thought that for collisions with many platforms I just needed to put an array of platforms through collision check instead of one platform, but I was wrong.
I get my platform array from level map which is string array. So far I have encountered these problems:
1) If platform width or height is changed it also changes the platform
position and no matter how hard I tried I couldn't find why.
2) If I only put one platform in the map (if there is only one platform in the
array), player falls throught the platform and even through the ground.
3) If there is more than one platform, collision works best on last created:
*Top collision works only if at the start of the level, when player is
falling down, he falls down only on the platfor that was created last and
it works perfectly. You can jump as many times as you want, until you land
on the ground. After that the top collision dissapears.
*Sides collision works all the time. The platform that was created last
works perfectly. While the player goes inside other platforms a little bit
while I'm holding the joystic, just after I realease the joystick it goes
back to the possition where it shoud be when colliding.
I read in the Stackoverflow article "C# Platform Collisions Not Working With Multiple Platforms" that if collision detected, the loop should be broken. I heve tried a few variations of it: for, foreach, while with bool, but all of them made game lag awfully (foreach lags even without break). Using brake should do quite an opposite of slowing down the game.
4) Collisions work only in the groud map level (map[11]).
Thank you four your time, I would highly appreciate an answer to any of my questions.
------------------------------------------------------------CODE-------------------------------------------------------------
This part is responsible for platforms map and array. Collisions work only in ground level (map[11]).
//Map generation
// -88 this offset makes the platform align with botom of the screen
int basePositionTop = -88;
int basePositionLeft = 0;
int platformId = 0;
int playerHeight = 30;
int playerWidth = 30;
Platform[] platformMap = new Platform[200];
void SetupUI()
{
// initialize window
mainWindow = displayT43.WPFWindow;
// setup the layout
layout = new Canvas();
Border background = new Border();
background.Background = new SolidColorBrush(Colors.Black);
background.Height = 272;
background.Width = 480;
layout.Children.Add(background);
Canvas.SetLeft(background, 0);
Canvas.SetTop(background, 0);
//add the player
player = new Rectangle(playerWidth, playerHeight);
player.Fill = new SolidColorBrush(Colors.Red);
layout.Children.Add(player);
// Platformer map
string[] map = new string[12];
map[0] = ".....................................";
map[1] = ".....................................";
map[2] = ".....................................";
map[3] = ".....................................";
map[4] = ".....................................";
map[5] = ".....................................";
map[6] = ".....................................";
map[7] = ".....................................";
map[8] = ".....................................";
map[9] = ".....................................";
map[10] = ".....................................";
map[11] = ".....#..#............................";
for (int i = 0; i < map.Length; i++)
{
for (int j = 0; j < map[i].Length; j++)
{
if (map[i][j] == '#')
{
platformMap[platformId] = new Platform(platWidth, platHeight);
platformMap[platformId].set(basePositionLeft + j * platWidth , basePositionTop + i * platHeight);
platformId++;
}
}
}
// Adding platforms to screen
for (int i = 0; i < platformId; i++)
{
layout.Children.Add(platformMap[i].get());
}
mainWindow.Child = layout;
}
This part is reponsible for collision detection as well as for actions when top or bottom collision is detected.
int power;
int jumpPower = 36;
bool jumped = true;
int playerTopPosition;
int playerLeftPosition = 250;
void jumpTimer_Tick(GT.Timer timer)
{
double y = joystick.GetPosition().Y;
//Jump part
if (!jumped) // if didn't jump
{
if (y >= 0.7) // and jumps
{
jumped = true;
power = jumpPower;
}
}
//Jump
if (jumped)
{
playerTopPosition -= power;
power -= 8;
}
// update player top position
Canvas.SetTop(player, playerTopPosition);
// Platform check loop
for (int i = 0; i < platformId; i++)
{
//TOP AND BOTTOM COLLISION
//Check if player is in platform bounds x axis
if ((playerLeftPosition + playerWidth) >= platformMap[i].posLeft()
&& playerLeftPosition <= platformMap[i].posLeft() + platWidth)
{
//TOP collision. (platHeight/2 -1) - even if player is in platform
// (from top) and doesn't touch the middle he is set on top
if (playerTopPosition + playerHeight >= platformMap[i].posTop()
&& playerTopPosition + playerHeight <= platformMap[i].posTop() + (platHeight / 2 - 1))
{
playerTopPosition = platformMap[i].posTop() - playerHeight;
jumped = false;
}
//BOTTOM collision. (platHeight/2 + 1) - even if player is in platform
//(from bottom) and don't touch the middle he collides with bottom
if (playerTopPosition <= platformMap[i].posTop() + platHeight
&& playerTopPosition >= platformMap[i].posTop() + (platHeight / 2 + 1))
{
playerTopPosition = platformMap[i].posTop() + platHeight;
power = -1;// without this player gets stuck on platform bottom
}
}
else jumped = true; // if player steps off platform - he falls
// the very bottom collision
if (playerTopPosition + playerHeight >= displayT43.Height)
{
playerTopPosition = displayT43.Height - playerHeight;
jumped = false;
}
//SIDES COLLISION
//Check if player is in platform bounds y axis
if (playerTopPosition + playerHeight <= platformMap[i].posTop() + platHeight
&& playerTopPosition >= platformMap[i].posTop())
{
//RIGHT collision. (platWidth / 2 - 1) - even if player is in platform
// (from left) and don't touch the middle he collides with left
if ((playerLeftPosition + playerWidth) + 1 >= platformMap[i].posLeft()
&& (playerLeftPosition + playerWidth) <= platformMap[i].posLeft() + (platWidth/2-1))
{
playerLeftPosition = platformMap[i].posLeft() - playerWidth;
stopRight = true;// stops moving right
}
else stopRight = false;
//LEFT collision. (platWidth / 2 - 1) - even if player is in platform
// (from right) and don't touch the middle he collides with right
if (playerLeftPosition - 1 <= platformMap[i].posLeft() + platWidth
&& playerLeftPosition >= platformMap[i].posLeft() + (platWidth / 2 + 1))
{
playerLeftPosition = platformMap[i].posLeft() + platWidth;
stopLeft = true;// stops moving left
}
else stopLeft = false;
}
else
{
stopRight = false;
stopLeft = false;
}
// update player top position
Canvas.SetTop(player, playerTopPosition);
}
}
This is responsible for left/rigth movements and actions when left or right collision is detected.
bool stopLeft = false;// makes stop move left
bool stopRight = false;// makes stop move right
void JoystickTimer_Tick(GT.Timer timer)
{
double x = joystick.GetPosition().X; // joystic x scale [-1;1]
// move left
if (x < -0.3 && playerLeftPosition > 0 && !stopLeft)
{
playerLeftPosition -= 5;
}
// move right
else if (x > 0.7 && playerLeftPosition < displayT43.Width - playerWidth
&& !stopRight)
{
playerLeftPosition += 5;
}
Canvas.SetLeft(player, playerLeftPosition);// update player left postion
}
Class Platform.cs
class Platform
{
private Rectangle platformRectangle { get; set; }
int left = 0;
int top = 0;
public Platform()
{
}
public Platform(int Width, int Height)
{
this.platformRectangle = new Rectangle();
this.platformRectangle.Height = Height;
this.platformRectangle.Width = Width;
platformRectangle.Fill = new SolidColorBrush(Colors.Orange);
}
public void set(int leftPosition, int topPosition)
{
Canvas.SetLeft(platformRectangle, leftPosition);
Canvas.SetTop(platformRectangle, topPosition);
this.left = leftPosition;
this.top = topPosition;
}
public Rectangle get()
{
return platformRectangle;
}
public int posLeft()
{
return left;
}
public int posTop()
{
return top;
}
}

Where is the infinite loop here that happens only on iPhone, but not in the editor?

Ok, Ive had this in past where infinite loops/freezes happen on device/iphone but not in editor - and no error message. No crash just freezes.
Ive run Debug.Logs and tried more delays but I dont know what is causing iPhone to freeze/some infinite loop here. FPS drops too, I checked.
Basically I tried to spawn a set number of objects on planes that grow and more get added to scene as this spawn process occurs. The spawn process stops once a max upper limit of objects has been exceeded.
Here's how I do this, works great in editor -
PART 1:
if(anchorManager.CloneNumberGet() > 0) //first was placed
{
hasTriedSpawn = true;
//StartCoroutine (spawnAllTiers (30));
TriggerTierSpawn(); //sets off whole thing
}
PART 2:
public void TriggerTierSpawn()
{
if (GameController.trackingReady) {
World w = worlds[currentWorld];
int max = w.numTiers + 10;
if (tiersSpawned.Length < max && AreThereEmptyPlanes () && max <= GameController.spawnLimit) {
planesFilled.ToList ().Sort ((pair1, pair2) => pair1.Value.CompareTo (pair2.Value));
//orderedPlanes = planesFilled.Keys.ToList ();
print ("Running this loop");
foreach (KeyValuePair<GameObject, float> entry in planesFilled) {
GameObject plane = entry.Key;
//print ("P: "+plane);
if (CheckForEmptySpace (plane.GetComponentInChildren<BoxCollider> ().bounds) != absurdVector3 && plane.GetComponentInChildren<BoxCollider> ().bounds
!= null && tiersSpawned.Length < max) {
StartCoroutine (spawnAllTiers (max, plane.GetComponentInChildren<BoxCollider> ().bounds));
}
//put a wait here
}
} else if (tiersSpawned.Length < max) {
print ("Wait for more planes");
} else {
//print ("REACHED MAX: "+max+" Num tiers: "+tiersSpawned.Length);
}
}
}
public Vector3 CheckForEmptySpace (Bounds bounds)
{
float sphereRadius = tierDist;
Vector3 startingPos = new Vector3 (UnityEngine.Random.Range(bounds.min.x, bounds.max.x), bounds.min.y, UnityEngine.Random.Range(bounds.min.z, bounds.max.z));
// Loop, until empty adjacent space is found
var spawnPos = startingPos;
while ( true )
{
if (!(Physics.CheckSphere(spawnPos, sphereRadius, 1 << 0)) ) // Check if area is empty
return spawnPos; // Return location
else
{
// Not empty, so gradually move position down. If we hit the boundary edge, move and start again from the opposite edge.
var shiftAmount = 0.5f;
spawnPos.z -= shiftAmount;
if ( spawnPos.z < bounds.min.z )
{
spawnPos.z = bounds.max.z;
spawnPos.x += shiftAmount;
if ( spawnPos.x > bounds.max.x )
spawnPos.x = bounds.min.x;
}
// If we reach back to a close radius of the starting point, then we didn't find any empty spots
var proximity = (spawnPos - startingPos).sqrMagnitude;
var range = shiftAmount-0.1; // Slight 0.1 buffer so it ignores our initial proximity to the start point
if ( proximity < range*range ) // Square the range
{
Debug.Log( "PLANE FULL - an empty location could not be found" ); //means plane is FULL
return absurdVector3;
}
}
}
}
PART 3:
public IEnumerator spawnAllTiers(int maxNum, Bounds bounds)
{
while (tiersSpawned.Length < maxNum) { //still has space
Tier t = getNextTier ();
//Vector3 newPos = new Vector3 (UnityEngine.Random.Range(GetGrid ().bounds.min.x, GetGrid ().bounds.max.x), GetGrid ().bounds.min.y, UnityEngine.Random.Range(GetGrid ().bounds.min.z, GetGrid ().bounds.max.z));
Vector3 newPos = CheckForEmptySpace (bounds);
if(bounds.Contains(newPos) && t) //meaning not 200 so it is there
{
spawnTier (newPos, t);
}
platformsSpawned = GameObject.FindObjectsOfType<Platform> ();
tiersSpawned = GameObject.FindObjectsOfType<Tier> ();
yield return new WaitForSeconds (0.3f); //increase this if have iphone problem
//START NEW --------------------
if (CheckForEmptySpace (bounds) == absurdVector3 && tiersSpawned.Length < maxNum)
{
break;
}
}
//maybe check for num times trying, or if size of all spawned tiers is greater than area approx
}
Tier getNextTier()
{
Tier p = null;
int j = UnityEngine.Random.Range (0, worlds [currentWorld].tiers.Count);
p = worlds [currentWorld].tiers[j];
return p;
}
//SPAWN NEXT TIER
public void spawnTier(Vector3 position, Tier t) //if run out of plats THEN we spawn up like tree house
{
print ("SUCCESS - spawn "+position+"SPHERE: "+Physics.CheckSphere(position, tierDist, 1 << 0));
Instantiate (t, position, Quaternion.identity);
anchorManager.AddAnchor(t.gameObject);
}
I have no idea what to do here. Ideally I just need to fill up the planes, IF the max num objects hasnt been reached, as they come into existence.
EDIT- tried:
if(bounds.Contains(newPos) && t) //meaning not 200 so it is there
{
spawnTier (newPos, t);
} else {
break;
}
and just spawnTier (newPos, t);
This looks dangerous
if(bounds.Contains(newPos) && t) //meaning not 200 so it is there
{
spawnTier (newPos, t);
}
you are relying on this to get out of the while loop, but if the condition never happens, then you are stuck. Given it takes some kind of bounds, potentially on platform you get a condition where this never happens. Or you are running out of tiers, and t is forever preventing getting into this section of code
I think you need an else clause if you don't spawn anything to make sure you get out of the loop.

Remembering a direction, moving to a point, then changing direction. XNA

I'm making a pacman clone in XNA.
So far I've drawn the tile map using 2D array, added the pills using another 2D array and made a 2D array that allows movement of pacman.
In the actual game you can press right whilst moving up, and it will wait until you're able to move right and the turn.
I have a system in place that allows a turn only when the spritePosition % 32 = 16.
This means the sprite will be centred between the walls.
I need the program to remember the last key pressed or move to the right position before turning, but i cant find a way of doing it.
Here is a bit of the code that covers what I'm trying.
public void MovementCheck()
{
presentKey = Keyboard.GetState();
spritePosition = spriteVelocity + spritePosition;
pacManRec = new Rectangle((int)spritePosition.X, (int)spritePosition.Y, pacManTex.Width, pacManTex.Height);
spriteOrigin = new Vector2(pacManRec.Width / 2, pacManRec.Height / 2);
//Press Right
if (presentKey.IsKeyDown(Keys.Right) && pastKey.IsKeyUp(Keys.Right))
{
Right();
}
}
private void Right()
{
direction = "right";
//if the next block in tile map to the right is a 1, and the sprite is centred - allow a turn
if (inputMap[(int)Math.Floor(spritePosition.Y / 32), (int)Math.Floor(spritePosition.X / 32) + 1] == 1 && (spritePosition.Y % 32 == 16))
{
rotation = ((float)Math.PI / 180);
spriteVelocity.X = 0;
spriteVelocity.Y = 0;
spriteVelocity.X = movementSpeed;
}
}
Only the right key is shown, the others are similar but the directions all change and the checks to the tile map are changed accordingly. (+1 on the X here)
ive tried things like
while (spritePosition.Y % 32 != 16)
{ spritePosition = spriteVelocity + spritePosition; }
but that just makes the sprite shoot up the screen, (kinda obviously) :(
and I tried a new Method before the Right() call
bool RightCheck()
{
if ( CONDITIONS MET HERE )
return true
else
{
//dont remember if I used this line, but something similar
spritePosition = spriteVelocity + spritePosition;
RightCheck()
}
return false; //allows program to build
}
Just an causes infinite recursion.
One solution is adding a int counter = 0; which you update in your gameloop (with counter++;) every frame/time-step. Set to 0 everytime you make a valid input and save that input.
Outlined code:
public class GameClassWhereUpdateIsDone
{
private enum Directions { None, Up, Down, Left, Right };
private int counter = 0;
private Directions currentDirection; // Current movement-direction
private Directions lastInput; // Last direction from input
public void Update(...)
{
var keyboardState = Keyboard.GetState();
if(keyboardState.IsKeyPressed(Keys.Right))
{
counter = 0;
direction = Directions.Right;
}
if(currentDirection != lastInput && counter < 5) // Allow turning 5 updates ahead.
{
// Player want to turn
if(AllowedToTurn(lastInput)
{
currentDirection = lastInput;
}
}
MoveDirection(currentDirection);
counter++;
}
private bool AllowedToTurn(Directions direction)
{
if(direction == Directions.Right)
{
return RightCheck();
}
}
}
The key idea is to keep track of movement direction and last direciton that was input...
In the original Pac-Man "pre-turning" was actually used, meaning you would start moving diagonally if you turned ahead of a corner according to: http://home.comcast.net/~jpittman2/pacman/pacmandossier.html which is an interesting read.

having trouble implementing physics to ball collision program

I'm currently working on a simple ball collision program in C#, where an indeterminate amount of balls bounce around the screen, each being added to the program on a button click. So far I've gotten everything working, and I have a basic collision system. Now, I'm trying to add more realistic physics to the balls.
The thing is, I have little understanding of physics. I've been reading a bit about vector physics and I get the gist of it, but I'm not quite making the connection between what I've read and how I'm supposed to implement these concepts programmatically. Could anybody provide me some resources on how one is actually supposed to implement vector physics to something like a simple ball collision program like I've written?
Here's what I have right now. It's basically just two booleans determining whether my ball goes in one of four directions. When two balls collide, they just pass their directions to each other.
public void newball(PaintEventArgs e, int panelWidth, int panelHeight)
{
//Detects walls of form. if it detects a wall or another ball, it bounces
if (X >= panelWidth)
{
bounceX = true;
}
else if (X <= 25)
{
bounceX = false;
}
if (Y >= panelHeight )
{
bounceY = true;
}
else if (Y <= 25)
{
bounceY = false;
}
//balls only go in four directions right now have to implement vector physics.*/
if (bounceX == false)
{
X = X+2;
}
else if (bounceX == true)
{
X = X -2;
}
if (bounceY == false)
{
Y = Y+2;
}
else if (bounceY == true)
{
Y = Y-2;
}
//this draws the ball on the panel.
Pen clsPen = Pens.Black;
Color color = Color.Black;
SolidBrush brush = new SolidBrush(color);
e.Graphics.DrawEllipse(clsPen, X - 25, Y -25, 25, 25);
e.Graphics.FillEllipse(brush, X-25, Y-25, 25, 25);
}
And here are some of the things I've read:
2D Collisions, Vectors

Multi Direction Bullets[read]

Been trying to code something for a while for a project im still working on for school, even though it's done.
I want to make a grenade that shoots out bullets on enemies colliding with it, but what I need help with atm is making 8 bullets shoots in all different directions at once.
here's the code my teacher gave me to do it(I asked him for help)
if (mouse.LeftButton == ButtonState.Pressed)
{
Texture2D pewTexture;
pewTexture = game.Content.Load<Texture2D>("pew");
game.firingSound.Play();
//Tweak pews to shoot at mouse, rather than just going straight on the y axis.
pew = new CPew(game, pewTexture);
pew.velocity = new Vector2((float)Math.Cos(rotation), (float)Math.Sin(rotation)) * 10f + spriteVelocity;
pew.position = position + pew.velocity * 5;
//easy cheesy way:
//pew.position = position;
//pew.position.X += 15f;
//pew.position.Y -= 20f;
//super awesome cool way for cool people and celebrities
pew.position = position +
new Vector2(
texture.Width * .2f - pew.texture.Width * .2f,
-pew.texture.Height);
game.pews.Add(pew);
myFiringDelay = 10;
}
else
{
if (mouse.RightButton == ButtonState.Pressed)
{
float pi2 = (float)Math.PI * 2.0f;
int numShots = 10;
float pi2overnum = pi2 / numShots;
for (int i = 0; i < numShots; i++)
{
Vector2 direction = PiToVec2(pi2overnum * i);
//particles[i].reset(position,direction, vector2.zero, 6);
game.pews[i].Reset(pew.position, direction, Vector2.Zero);
}
Vector2 PiToVec2(float piT)
{
return new Vector2((float)Math.Sin(piT), (float)Math.Cos(piT));
}
apparently this will make it shoot in every direction on mouse right click but every time I try it and my game crashes straight up
Then we have a pew class which is bullets and thats what I want to be shot in those directions at the same time
you guys may not be able to help with the code i've shown you, i've spent a while looking for a way to do this but i can't seem to find anything
A former example and or source code would be really helpful, just at least another way to look at this thanks.
Showingme when it crashed, it tells me index goes out of range or is negative, if you guys could just show me base code for multidirectional bullets id be happy
The problem your having is that when you try and loop through your game.pews collection you are trying to call Reset() on the first 10 items in the collection. However there appear to not be 10 pews in there. So when you get to the end and try to access the next one, that's where you get the "Index out of range" error.
For your 8 bullets from a grenade part of the question, I think you want to do something like this.
//Once a grenade has collided with an enemy
float pi2 = (float)Math.PI * 2.0f;
int numShots = 8;
float pi2overnum = pi2 / numShots;
for (int i = 0; i < numShots; i++)
{
Vector2 direction = PiToVec2(pi2overnum * i);
pew = new CPew(game, pewTexture);
pew.velocity = new Vector2((float)Math.Cos(rotation), (float)Math.Sin(rotation)) * 10f + spriteVelocity;
//Set the position based off of the grenades last position.
//Set the direction.
//Set any other attributes needed.
game.pews.Add(pew);
}
Now you have eight bullets moving in different directions from where the grenade exploded.
To update them and draw them I would recommend using a foreach loop so you don't have to worry about "Index out of range" errors.
foreach CPew pew in game.pews
{
pew.Update();
}

Categories