sbrez
sbrez

Reputation: 9

How can I correct a slightly off vector movement in java (2D game)

I am making a 2D top-down shooter in Java (uni project) but hit a problem with bullet aiming - I am unsure why the angle is incorrect, and how to correct it.

The player shoots bullets at the cursor location on mousedown. I am using dx/y = (x/ytarget - x/yorigin), normalising and incrementing the bullets x/y pos with dx each tick.

When the cursor is moved, the firing angle tracks the cursor - but the angle is off by 45 degrees or so The white circle is player, red is cursor and bullets the yellow dots.

I dont have rep to post images (first post), here is a link that shows the error of the angle.

http://i.imgur.com/xbUh2fX

Here is the bullet class:

note - update() is called by the main game loop

import java.awt.*;
import java.awt.MouseInfo;

public class Bullet {

private double x;
private double y;
private int r;

private double dx;
private double dy;
private double speed;
private double angle;
private Point c;

private Color color1;

public Bullet(int x, int y) {

    this.x = x;
    this.y = y;
    r = 3;
    speed = 30;
    color1 = Color.YELLOW;

    c = MouseInfo.getPointerInfo().getLocation();

// getting direction 
    dx = c.x - x;
    dy = c.y - y;
    double distance = Math.sqrt(dx*dx + dy*dy);
    dx /= distance;
    dy /= distance;

}

public boolean update() {

    x += dx*speed;
    y += dy*speed;

    if(x < -r || x > GamePanel.WIDTH + r ||
        y < -r || y > GamePanel.HEIGHT + r) {
        return true;
    }

    return false;

}

public void draw(Graphics2D g) {

    g.setColor(color1);
    g.fillOval((int) (x - r), (int) (y - r), 2 * r, 2 * r);

}

}

Upvotes: 0

Views: 175

Answers (1)

ARaccoonGames
ARaccoonGames

Reputation: 1

I got a similar game and this is the code I used

import java.awt.Graphics2D;

import araccoongames.pongadventure.game.Entity;
import araccoongames.pongadventure.game.Game;
import araccoongames.pongadventure.game.MapLoader;

public class Ball extends Entity {

private float speed = 8;
private float speedx;
private float speedy;
private float degree;

public Ball(float posx, float posy, Game game) {
    super(0, 0, game);

    this.posx = posx;
    this.posy = posy;

    // posx = ball x position
    // posy = ball y position
    // game.input.MOUSEY = mouse y position
    // game.input.MOUSEX = mouse x position

    degree = (float) (270 + Math.toDegrees(Math.atan2(posy - game.input.MOUSEY, posx - game.input.MOUSEX))) % 360;

    speedx = (float) (speed * Math.sin(Math.toRadians(degree)));
    speedy = (float) (speed * Math.cos(Math.toRadians(degree)));
}

@Override
public void render(Graphics2D g) {
    drawImage(game.texture.SPRITE[0][1], g);
}

@Override
public void update() {
    posx += speedx;
    posy -= speedy;

}

}

Upvotes: 0

Related Questions