第85集:太阳系模型Planet类的实现构造器的优化和调用
今天遇到了一件恶心事,被人钓鱼执法了,心情不太好,后续估计还有很多麻烦事,但是,我不能允许它影响我的学习进度,加油,王涛!没有什么事情能阻止你实现目标!
本集知识点
-
重构代码,让构造函数互相调用,前期虽然麻烦,但后期非常省事,例如本例对Star类的重构。
package com.test084_087_solar; import java.awt.Graphics; import java.awt.Image; import com.test084_087_util.GameUtil; public class Star { Image img; double x,y; int width,height; public void draw(Graphics g){ g.drawImage(img,(int)x,(int)y,null); } public Star(){ } public Star(Image img){ this.img = img; this.width = img.getWidth(null); this.height = img.getHeight(null); } public Star(Image img,double x,double y){ this(img); this.x = x; this.y = y; } public Star(String imgpath,double x,double y){ this(GameUtil.getImage(imgpath),x,y); } }
-
关注Planet类如何沿着椭圆路径飞行。
//Planet类的实现 package com.test084_087_solar; import java.awt.Graphics; import java.awt.Image; import com.test084_087_util.GameUtil; public class Planet extends Star{ //除了图片,坐标。行星沿着某个椭圆运行:长轴、短轴、速度。绕着某个Star飞。 double longAxis; //椭圆长轴 double shortAxis; //椭圆短轴 double speed; //飞行的速度 double degree; Star center; public Planet(Star center,String imgpath,double longAxis,double shortAxis,double speed){ super(GameUtil.getImage(imgpath)); this.center = center; this.x = center.x + longAxis; this.y = center.y; this.longAxis = longAxis; this.shortAxis = shortAxis; this.speed = speed; this.center = center; } public Planet(Image img,double x,double y){ super(img,x,y); } public void draw(Graphics g){ g.drawImage(img,(int)x,(int)y,null); //沿着椭圆轨迹飞行 x = (center.x + center.width/2) + longAxis*Math.cos(degree); y = (center.y + center.height/2) + shortAxis*Math.sin(degree); degree += speed; } }
package com.test084_087_solar; import java.awt.Graphics; import java.awt.Image; import com.test084_087_util.Constant; import com.test084_087_util.GameUtil; import com.test084_087_util.MyFrame; public class SolarFrame extends MyFrame { Image bg = GameUtil.getImage("images/bg.jpg"); Star sun = new Star("images/sun.jpg",Constant.GAME_WIDTH/2,Constant.GAME_HEIGHT/2); Planet earth = new Planet(sun,"images/earth.jpg",150,100,0.1); public void paint(Graphics g){ g.drawImage(bg,0,0,null); sun.draw(g); earth.draw(g); } public static void main(String[] args){ new SolarFrame().launchFrame(); } }