• 2D Shooter Help
    5 replies, posted
This should just be basic trig but for some reason I can't get it to work right. I'm trying to make a bullet shoot from the player position towards the mouse position like a 2D shooter but something is wrong. It works out fine on paper I just don't know whats wrong here. When I have the mouse somewhere above the player and "shoot" it seems to work fine until i move my mouse down around 45 degrees or so then it shoots off in one position until i move the mouse back up. It's weird...here's the gist of it: [cpp] static public void Shoot() { ... Point mouse = Mouse.MousePosition; Point offset = new Point(mouse.X - position.X, mouse.Y - position.Y); angle = Math.Atan(offset.Y / offset.X); if (offset.X > 0 && offset.Y < 0) quadrant = 0; else if (offset.X > 0 && offset.Y > 0) quadrant = 1; else if (offset.X < 0 && offset.Y > 0) quadrant = 2; else if (offset.X < 0 && offset.Y < 0) quadrant = 3; bullets[i].Create(bulletSurface, angle, position, 15, quadrant); ... } class Bullet { public void Create(Surface newSurface, double angle, Point newPosition, double speed, int quadrant) { ... velocity.X = (int)((Math.Cos(angle) * speed) + 0.5); velocity.Y = (int)((Math.Sin(angle) * speed) + 0.5); if(quadrant == 2 || quadrant == 3) { velocity.X = -velocity.X; velocity.Y = -velocity.Y; } ... } } [/cpp]
Why not use vectors instead of trig?
[cpp]float ang=atan2 (mousey - posy , mousex - posx); float bulletxvel=cos(ang) * BULLET_VELOCITY; float bulletyvel=sin(ang) * BULLET_VELOCITY; [/cpp] atan2 replaces all your ifs.
[QUOTE=Sporbie;15982428][cpp]float ang=atan2 (mousey - posy , mousex - posx); float bulletxvel=cos(ang) * BULLET_VELOCITY; float bulletyvel=sin(ang) * BULLET_VELOCITY; [/cpp] atan2 replaces all your ifs.[/QUOTE] Oh wow, thank you so much. That fixed everything :D
[QUOTE=Spartan117;15981236] [cpp] static public void Shoot() { ... Point mouse = Mouse.MousePosition; Point offset = new Point(mouse.X - position.X, mouse.Y - position.Y); angle = Math.Atan(offset.Y / offset.X); if (offset.X > 0 && offset.Y < 0) quadrant = 0; else if (offset.X > 0 && offset.Y > 0) quadrant = 1; else if (offset.X < 0 && offset.Y > 0) quadrant = 2; else if (offset.X < 0 && offset.Y < 0) quadrant = 3; bullets[i].Create(bulletSurface, angle, position, 15, quadrant); ... } [/cpp][/QUOTE] Wow, you must be leaking memory like an anus and a stack of fat-free pringles. Try not to use the 'new' operator when you don't need variables beyond that certain scope.
[QUOTE=Cathbadh;16041551]Wow, you must be leaking memory like an anus and a stack of fat-free pringles. Try not to use the 'new' operator when you don't need variables beyond that certain scope.[/QUOTE] Luckily, it's C# so none of that matters. :buddy:
Sorry, you need to Log In to post a reply to this thread.