简体   繁体   中英

Java libgdx Shooting bullet at direction with constant speed

I am trying to get my bullets to fire towards (input coords) at a constant speed. So far I was able to get it to shoot at the direction but the farther I click (touch, android game) the faster the bullet goes. I have tried different methods by scaling but failed miserably, I have started coding just a month ago and using this as a project to increase my knowledge of how things work before I work on a full game but having too much trouble with this.

This is what I have been using to get the bullet to move towards the direction I want it to, the codes with // in front were other samples I got while browsing through the internet in hopes of getting what I wanted. I have thought of not using velocity to set the direction, but I have no clue of another method for this.

EDIT: All in short, I cannot get all the bullets to move in the same speed, farther I click, higher velocity bullet has.

Any help guys? Thanks a bunch

Player Class :

    public void update(float delta) {
    if (Gdx.input.isTouched()) {
        if (System.currentTimeMillis() - lastShot >= FIRE_RATE) {
            bullets.add(new Bullet(position.x + 6,position.y + 6,4,4,Gdx.input.getX() / 2,Gdx.input.getY() / 2));
            lastShot = System.currentTimeMillis();
        }
    }
    for (int i=0;i<bullets.size();i++) {
        bullets.get(i).update(delta);
    }
}

Bullet Class :

    public Bullet(float x, float y, int width, int height, float targetX, float targetY) {
    this.width = width;
    this.height = height;
    position = new Vector2( x , y );
    velocity = new Vector2( 0 , 0 );
    velocity.set(targetX - position.x,targetY - position.y);
    //velocity.set(targetX - position.x, targetY - position.y).nor().scl(Math.min(position.dst(targetX, targetY), speedMax));
}

public void update(float deltaTime) {
    //position.add(position.x + speedMax * deltaTime * ax,position.y + speedMax * deltaTime * ay);
    position.add(velocity.x * deltaTime, velocity.y * deltaTime);
    //velocity.scl(1 - (0.98f * deltaTime)); 
    // Linear dampening, otherwise the ball will keep going at the original velocity forever
    }

Well, normalizing vectors should be rather straightforward. Take your components, square them, and add them together (pythagorean theorem) and then divide each component by this result. Ie vX = (targetX - position.x)/Math.sqrt(((targetX - position.x) * (targetX - position.x)) + ((targetY - position.y) *(targetY - position.y )))

Then you can multiply vX by some constant, and do the same for a vY and then set your velocity.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM