0

I am trying to fire bullets from the location of the gun that is firing. So when the mouse is moved the gun moves at a direction. I would like the bullet to move at the direction which the gun is pointing to. So i can fire at any direction.

Ive tried using the turntowards() method. but the bullets only shot to the right of the screen despite where it is rotated.

Any suggestions?

I have a character class :

import greenfoot.*;  

public class Gun extends Actor
{
    private int speed;
    public void act() 
    {
        // Add your action code here.
        MouseInfo mouse = Greenfoot.getMouseInfo();
        if (mouse !=null)
            setRotation((int)(180*Math.atan2(mouse.getY()-getY(),mouse.getX()-getX())/Math.PI));
            move(speed);

            if(Greenfoot.mouseClicked(null))
            {
                getWorld().addObject(new bullet(getRotation()),getX(),getY());
                turnTowards(mouse.getX(), mouse.getY());

            }

    } 

}

I have a bullet class :

import greenfoot.*;  

public class bullet extends Actor
{
    private int direction;

    public void act() 
    {

        setLocation(getX()+5,getY());

    }    
    public bullet(int dir)
    {
        this.direction=dir;
    }
}

And i have a baddie class :

import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)

/**
 * Write a description of class balloon here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class baddie extends Actor
{

    public void act() 
    {

        setLocation(getX(), getY()-1);

    }    

}
Amith
  • 6,818
  • 6
  • 34
  • 45
Pro-grammer
  • 862
  • 3
  • 15
  • 41
  • By the by, remember the Java standard is that class names have upper case first letters. Obviously syntactically acceptable, but can make things confusing sometimes. – Paul Richter Oct 29 '13 at 16:35

1 Answers1

1

The problem is that your bullet::act method is not doing what you expect. Instead of following the direction you are simply moving the bullet to the right (by adding +5 to x-axis each time act is called). P.S.: I am assuming that bullet::act is the method you are calling in the gameloop.

Your direction is an integer value representing the angle in radians, right? It would be better to represent the direction as a 2D vector and translate the bullet according to it, since then you can represent both the direction and the speed as a single velocity vector. Some interesting refefences to help you with that: http://natureofcode.com/book/chapter-1-vectors/ and http://www.red3d.com/cwr/steer/ (specially the seek behaviour).

Cheers Luiz

Luiz Vieira
  • 570
  • 11
  • 35
  • Btw, here is a sample Vector2D class that can help you to start. :) http://code.google.com/p/rasterengine/source/browse/src/com/Math/Vector2D.java?r=2a77e099bfb1c7d22641ee585766f1377a798d87&spec=svn2a77e099bfb1c7d22641ee585766f1377a798d87 – Luiz Vieira Oct 29 '13 at 16:41