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);

    }    

}
4

1 回答 1

1

问题是您的 bullet::act 方法没有达到您的预期。您只需将子弹向右移动(每次调用 act 时向 x 轴添加 +5),而不是跟随方向。PS:我假设 bullet::act 是您在游戏循环中调用的方法。

你的方向是一个整数值,以弧度表示角度,对吧?最好将方向表示为 2D 矢量并根据它平移子弹,因为这样您就可以将方向和速度表示为单个速度矢量。一些有趣的参考资料可以帮助您:http://natureofcode.com/book/chapter-1-vectors/http://www.red3d.com/cwr/steer/ 特别是搜索行为)。

干杯路易斯

于 2013-10-29T16:33:31.060 回答