我正试图从射击枪的位置发射子弹。因此,当鼠标移动时,枪会朝一个方向移动。我希望子弹朝着枪指向的方向移动。所以我可以朝任何方向射击。
我尝试过使用turntowards()
方法。但是子弹只是在屏幕右侧射击,尽管它在哪里旋转。
有什么建议吗?
我有一个字符类:
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());
}
}
}
我有一个子弹类:
import greenfoot.*;
public class bullet extends Actor
{
private int direction;
public void act()
{
setLocation(getX()+5,getY());
}
public bullet(int dir)
{
this.direction=dir;
}
}
我有一个 baddie课程:
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);
}
}
答案 0 :(得分:1)
问题是你的bullet :: act方法没有达到预期效果。您只需将子弹向右移动(通过每次调用act时向x轴添加+5),而不是按照方向。 P.S。:我假设bullet :: act是你在游戏循环中调用的方法。
你的方向是一个整数值,用弧度表示角度,对吧?将方向表示为2D矢量并根据它转换子弹会更好,因为那时您可以将方向和速度表示为单个速度矢量。一些有趣的答案可以帮助您:http://natureofcode.com/book/chapter-1-vectors/和http://www.red3d.com/cwr/steer/(特别是寻求行为)。
干杯 路易斯