Note that there are some explanatory texts on larger screens.

plurals
  1. POShoot to the mouse direction
    primarykey
    data
    text
    <h2>The problem:</h2> <p>I've got this "Shot" class. In the code, the target variables are the mouseX and mouseY. So when i click the mouse button, my player class will create a new shot object. But the shooting is inaccurate. How can i calculate the correct dx and dy?</p> <p>If i add the dx and dy to the "bullet's" x and y, the bullet will move to the mouse's direction.This is what i want. The mouse position is stored in targetX and targetY, when the object is created. This is the point what the oval wants to reach.</p> <p><strong>Links:</strong></p> <blockquote> <p><a href="https://www.dropbox.com/s/dhvf5vbqj25sgyw/game.jar" rel="nofollow"><strong><em>The game (finished)</em></strong></a><br/></p> </blockquote> <p><strong>The code (from Shot.java):</strong> </p> <pre><code>public class Shot extends Entity { private float targetX, targetY; public Shot(World world, float x, float y, int width, int height, Color color, float targetX, float targetY) { super(world, x, y, width, height, color); this.targetX = targetX; this.targetY = targetY; } @Override public void render(GameContainer gc, Graphics g, Camera camera) { g.setColor(color); g.fillOval(x - camera.getX(), y - camera.getY(), width, height); } @Override public void update(GameContainer gc, int delta) { float dx = targetX - x; float dy = targetY - y; x += dx * delta * .001f; y += dy * delta * .001f; } } </code></pre> <p><strong>I tried this, but still not work:</strong></p> <pre><code>@Override public void update(GameContainer gc, int delta) { float length = (float) Math.sqrt((targetX - x) * (targetX - x) + (targetY - y) * (targetY - y)); double dx = (targetX - x) / length * delta; double dy = (targetY - y) / length * delta; x += dx; y += dy; } </code></pre> <p><strong>I did it! Here is my solution:</strong> <br/> The problem was that, the target was the window's mouse position, and not the world's mouse position. <br/></p> <p>This is how i calculated the world's mouse positions: <br/></p> <pre><code>float mouseWorldX = x + (mouseX - screen_width / 2); // x = player's x position float mouseWorldY = y + (mouseY - screen_height / 2); // y = player's y position </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload