Sign in to follow this  
klrr

Need help implementing shooting

Recommended Posts

klrr    127

I want to make a top-down shooter but I am unsure how to write the shooting. I know how to get the angle but I don't know how to calculate how and what I should apply to the X and Y position to the bullet that spawns each frame, can anyone explain how you do this>

Share this post


Link to post
Share on other sites
klrr    127

Nevermind, I found out:

 

"Don't use angles: Compute the vector from the shooter to the mouse and normalize it (i.e. divide it by its length). Then advance the position of the bullet by adding that vector multiplied by the bullet's speed." - Álvaro

Share this post


Link to post
Share on other sites
Buckeye    10747

Tried the thing in the quote and it doesn't work.

 

Uh.. are you just making a statement, or is there some code you could post, maybe describing what "it" is? Alvaro's method is a common way to do that sort of thing, and the method works.

Share this post


Link to post
Share on other sites
klrr    127

Works kind of now. So it shoots bullets but they are shot in strange direction (not where I click). Here is code, java libgdx.

 

package com.deadsimple.zombiedown;

import com.badlogic.gdx.math.Vector2;

public class Bullet extends Sprite {
    
    public Bullet(Vector2 start, Vector2 dest) {
        super(start.x, start.y, 50, 50, 100);
        float deltaX = dest.x - start.x;
        float deltaY = dest.y - start.y;
        
        float length = (float) Math.sqrt(deltaX * deltaX + deltaY * deltaY);
        this.velocity.x = (deltaX / length) * this.SPEED;
        this.velocity.y = (deltaY / length) * this.SPEED;
    }
    
    public void update(float dt) {
        this.move();
        chackAlive();
    }

    private void chackAlive() {
        if (this.position.x > 480 || this.position.x < -50) this.alive = false;
        if (this.position.y > 800 || this.position.y < -50) this.alive = false;
        
    }
    
}

Share this post


Link to post
Share on other sites
Thinias    178

From a directional perspective, the implementation presented here looks correct to me.  I would check and see if the "dest" you passed in is actually where you thought it was.

Share this post


Link to post
Share on other sites
Orymus3    18821
also should call your function checkAlive (typo) and should not contain magic numbers (worst case make them a global constant for now so you keep your eyea on them)

Share this post


Link to post
Share on other sites
klrr    127

Thanks for all help, the problem was that I used the mouse position in the screen resolution, not as game world coordinates.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this