import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * Write a description of class Spaceship here. * * @author (your name) * @version (a version number or a date) */ public class Spaceship extends Actor { /** * Act - do whatever the Spaceship wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public void act() { doTurn(); doMove(); } private void doTurn() { if (Greenfoot.isKeyDown("left")) { turn(-4); } if (Greenfoot.isKeyDown("right")) { turn(4); } } private void doMove() { double radians = Math.toRadians(getRotation()); double moveSpeed = 5; double moveX = (int)(Math.cos(radians) * moveSpeed); double moveY = (int)(Math.sin(radians) * moveSpeed); setLocation(getX() + (int)moveX, getY() + (int)moveY); } }
时间: 2024-02-14 09:35:20 浏览: 147
Greenfoot-windows-361.msi
这段代码是一个用于Greenfoot游戏开发的Java类,它代表了一个太空飞船。在act()方法中,它调用了doTurn()和doMove()方法。doTurn()方法中检查了键盘输入,如果按下了左键,就向左旋转4度,如果按下了右键,就向右旋转4度。doMove()方法中,它根据飞船的旋转角度计算出移动的x和y轴的距离,然后调用setLocation()方法来移动飞船。这段代码看起来比较简单,但是实现了飞船的移动和转向功能,这是实现游戏的重要组成部分之一。
阅读全文