接着上一篇,我们完成后续的扫尾工作:游戏中个物体创建及其碰撞检测,分数保存,音效处理。


1.World类:(加入所有物体,及其碰撞检测,代码里有详细注解)

package com.zhf.mylibgdx;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import com.badlogic.gdx.math.Vector2;
/*** 统一管理世界中各个部分* @author ZHF**/
public class World {/**世界监听器接口**/public interface WorldListener {//跳跃public void jump ();//高跳public void highJump ();//碰撞public void hit ();//收集金币public void coin ();}//宽和高public static final float WORLD_WIDTH = 10;public static final float WORLD_HEIGHT = 15 * 20;//状态public static final int WORLD_STATE_RUNNING = 0;  //运行public static final int WORLD_STATE_NEXT_LEVEL = 1;  //下一关public static final int WORLD_STATE_GAME_OVER = 2;  //游戏结束//世界监听器public  WorldListener listener;//重力public static final Vector2 gravity = new Vector2(0, -12);//随机数public Random rand;public float heightSoFar; //public int score;public int state;//游戏中物体public final List<Platform> platforms;  //跳板public final Bob bob;  //主角public final List<Spring> springs;  //弹簧public final List<Squirrel> squirrels; //会飞的松鼠public final List<Coin> coins;  //金币public Castle castle;  //城堡public World(WorldListener listener) {this.listener = listener;//初始化游戏中的物体this.bob = new Bob(5, 1);this.platforms = new ArrayList<Platform>();this.springs = new ArrayList<Spring>();this.squirrels = new ArrayList<Squirrel>();this.coins = new ArrayList<Coin>();rand = new Random();generateLevel();  //生成关卡中除了Bob外所有的物体}/**生成关卡中除了Bob外所有的物体**/private void generateLevel() {float y = Platform.PLATFORM_HEIGHT / 2;float maxJumpHeight = Bob.BOB_JUMP_VELOCITY * Bob.BOB_JUMP_VELOCITY / (2 * -gravity.y);while (y < WORLD_HEIGHT - WORLD_WIDTH / 2) {int type = rand.nextFloat() > 0.8f ? Platform.PLATFORM_TYPE_MOVING : Platform.PLATFORM_TYPE_STATIC;float x = rand.nextFloat() * (WORLD_WIDTH - Platform.PLATFORM_WIDTH) + Platform.PLATFORM_WIDTH / 2;//跳板的位置Platform platform = new Platform(type, x, y);platforms.add(platform);//弹簧的位置if (rand.nextFloat() > 0.9f && type != Platform.PLATFORM_TYPE_MOVING) {Spring spring = new Spring(platform.position.x, platform.position.y + Platform.PLATFORM_HEIGHT / 2+ Spring.SPRING_HEIGHT / 2);springs.add(spring);}//松鼠的位置if (y > WORLD_HEIGHT / 3 && rand.nextFloat() > 0.8f) {Squirrel squirrel = new Squirrel(platform.position.x + rand.nextFloat(), platform.position.y+ Squirrel.SQUIRREL_HEIGHT + rand.nextFloat() * 2);squirrels.add(squirrel);}//金币的位置if (rand.nextFloat() > 0.6f) {Coin coin = new Coin(platform.position.x + rand.nextFloat(), platform.position.y + Coin.COIN_HEIGHT+ rand.nextFloat() * 3);coins.add(coin);}//游戏中的物体的位置根据跳板的位置来确定y += (maxJumpHeight - 0.5f);y -= rand.nextFloat() * (maxJumpHeight / 3);}//城堡的位置是确定的castle = new Castle(WORLD_WIDTH / 2, y);}/**刷新界面**/public void update(float deltaTime, float accelX) {updateBob(deltaTime, accelX);  //刷新主角updatePlatforms(deltaTime);  //刷新跳板updateSquirrels(deltaTime);  //刷新松鼠updateCoins(deltaTime);  //刷新金币if (bob.state != Bob.BOB_STATE_HIT) checkCollisions();//游戏结束判断checkGameOver();}/**碰撞检测**/private void checkCollisions() {// TODO Auto-generated method stubcheckPlatformCollisions();  //跳板的碰撞checkSquirrelCollisions();  //松鼠的碰撞checkItemCollisions();   //金币和弹簧的碰撞checkCastleCollisions();  //城堡的碰撞}/**跳板碰撞**/private void checkPlatformCollisions() {if (bob.velocity.y > 0) return;int len = platforms.size();for (int i = 0; i < len; i++) {Platform platform = platforms.get(i);if (bob.position.y > platform.position.y) {//调用工具类中矩形块碰撞检测if (OverlapTester.overlapRectangles(bob.bounds, platform.bounds)) {bob.hitPlatform();listener.jump();if (rand.nextFloat() > 0.5f) {platform.pulverize();}break;}}}}/**松鼠碰撞**/private void checkSquirrelCollisions () {int len = squirrels.size();for (int i = 0; i < len; i++) {Squirrel squirrel = squirrels.get(i);if (OverlapTester.overlapRectangles(squirrel.bounds, bob.bounds)) {bob.hitSquirrel();listener.hit();}}}/**金币和弹簧碰撞**/private void checkItemCollisions () {int len = coins.size();for (int i = 0; i < len; i++) {Coin coin = coins.get(i);if (OverlapTester.overlapRectangles(bob.bounds, coin.bounds)) {coins.remove(coin);len = coins.size();listener.coin();score += Coin.COIN_SCORE;  //加分}}if (bob.velocity.y > 0) return;  //若是上升状态不去考虑碰撞检测len = springs.size();for (int i = 0; i < len; i++) {Spring spring = springs.get(i);if (bob.position.y > spring.position.y) {//弹簧的碰撞检测if (OverlapTester.overlapRectangles(bob.bounds, spring.bounds)) {bob.hitSpring();listener.highJump();}}}}/**城堡的碰撞**/private void checkCastleCollisions () {if (OverlapTester.overlapRectangles(castle.bounds, bob.bounds)) {state = WORLD_STATE_NEXT_LEVEL;}}/**刷新Bob**/private void updateBob(float deltaTime, float accelX) {//碰撞跳板if (bob.state != Bob.BOB_STATE_HIT && bob.position.y <= 0.5f) bob.hitPlatform();//主角x轴方向移动的速度if (bob.state != Bob.BOB_STATE_HIT) bob.velocity.x = -accelX / 10 * Bob.BOB_MOVE_VELOCITY;bob.update(deltaTime);//竖直最大高度heightSoFar = Math.max(bob.position.y, heightSoFar);}/**刷新跳板**/private void updatePlatforms(float deltaTime) {int len = platforms.size();for (int i = 0; i < len; i++) {Platform platform = platforms.get(i);//取出集合中的跳板对象,调用其自身的刷新方法platform.update(deltaTime);//若状态为破碎状态,将该跳板对象移除出去if (platform.state == Platform.PLATFORM_STATE_PULVERIZING && platform.stateTime > Platform.PLATFORM_PULVERIZE_TIME) {platforms.remove(platform);len = platforms.size();}}}/**刷新松鼠**/private void updateSquirrels (float deltaTime) {int len = squirrels.size();for (int i = 0; i < len; i++) {Squirrel squirrel = squirrels.get(i);squirrel.update(deltaTime);}}/**刷新金币**/private void updateCoins (float deltaTime) {int len = coins.size();for (int i = 0; i < len; i++) {Coin coin = coins.get(i);coin.update(deltaTime);}}/**游戏结束判断**/private void checkGameOver () {//目前的Bob的高度小于场景的高度if (heightSoFar - 7.5f > bob.position.y) {state = WORLD_STATE_GAME_OVER;}}
}

       看着代码挺多,其实就是一个update()和checkCollisions(),还有重要的generateLevel()。接下来就是渲染WorldRenderer类中绘制各个物体


/**渲染游戏中各种物体(Bob,跳板,松鼠,弹簧,城堡,金币)**/private void renderObjects() {batch.enableBlending();batch.begin();renderPlatforms(); //绘制跳板renderBob(); //绘制主角renderItems();  //绘制金币和弹簧renderSquirrels();  //绘制松鼠renderCastle();  //绘制城堡batch.end();}

   

   由于代码过多,这里就不一一贴出来了,大家可以自行参考源码,有注解的哦!

既然添加了游戏中的物体,那自然又得在Asset中加载资源

声明:

//游戏中各种物体public static TextureRegion platform;  //跳板public static Animation brakingPlatform;  //破碎的跳板(动画)//主角public static Animation bobJump;  //跳跃(动画)public static Animation bobFall;  //下落(动画)public static TextureRegion bobHit;  //碰撞图片public static TextureRegion spring; //弹簧public static TextureRegion castle; //城堡public static Animation coinAnim;  //金币 (动画)public static Animation squirrelFly;  //飞着的松鼠 (动画)

实例化:

//游戏中各个物体platform = new TextureRegion(items, 64, 160, 64, 16);  //跳板brakingPlatform = new Animation(0.2f, new TextureRegion(items, 64, 160, 64, 16), new TextureRegion(items, 64, 176, 64, 16),new TextureRegion(items, 64, 192, 64, 16), new TextureRegion(items, 64, 208, 64, 16));//破碎的跳板spring = new TextureRegion(items, 128, 0, 32, 32);  //弹簧castle = new TextureRegion(items, 128, 64, 64, 64);  //城堡coinAnim = new Animation(0.2f, new TextureRegion(items, 128, 32, 32, 32), new TextureRegion(items, 160, 32, 32, 32),new TextureRegion(items, 192, 32, 32, 32), new TextureRegion(items, 160, 32, 32, 32));  //金币squirrelFly = new Animation(0.2f, new TextureRegion(items, 0, 160, 32, 32), new TextureRegion(items, 32, 160, 32, 32)); //飞着的松鼠//主角bobJump = new Animation(0.2f, new TextureRegion(items, 0, 128, 32, 32), new TextureRegion(items, 32, 128, 32, 32));bobFall = new Animation(0.2f, new TextureRegion(items, 64, 128, 32, 32), new TextureRegion(items, 96, 128, 32, 32));bobHit = new TextureRegion(items, 128, 128, 32, 32);

   运行一下代码,我们发现,我们操作者主角向上移动,会遇到弹簧,会破碎的跳板,飞着的松鼠,金币,一切都正常的运行着! 仔细一看,加上金币后分数值没有改变哦!当然还有死亡的判断,音效的加入等等。

效果图:


在此先做一个代码版本,方便初学者能够清楚的了解代码

×××:http://down.51cto.com/data/897211


下面我们来完成分值的计算:


在GameScreen中:

/**游戏运行状态**/private void updateRunning (float deltaTime) {if (Gdx.input.justTouched()) {guiCam.unproject(touchPoint.set(Gdx.input.getX(), Gdx.input.getY(), 0));//点击暂停if (OverlapTester.pointInRectangle(pauseBounds, touchPoint.x, touchPoint.y)) {Assets.playSound(Assets.clickSound);state = GAME_PAUSED;return;}}ApplicationType appType = Gdx.app.getType();// should work also with Gdx.input.isPeripheralAvailable(Peripheral.Accelerometer)if (appType == ApplicationType.Android || appType == ApplicationType.iOS) {world.update(deltaTime, Gdx.input.getAccelerometerX());} else {float accel = 0;if (Gdx.input.isKeyPressed(Keys.DPAD_LEFT)) accel = 5f;if (Gdx.input.isKeyPressed(Keys.DPAD_RIGHT)) accel = -5f;world.update(deltaTime, accel);}//当前分数(变化)if (world.score != lastScore) {lastScore = world.score;scoreString = "SCORE: " + lastScore;}//本关结束if (world.state == World.WORLD_STATE_NEXT_LEVEL) {state = GAME_LEVEL_END;}//游戏结束,分值计算if (world.state == World.WORLD_STATE_GAME_OVER) {state = GAME_OVER;if (lastScore >= Settings.highscores[4])scoreString = "NEW HIGHSCORE: " + lastScore;elsescoreString = "SCORE: " + lastScore;//获取最后分数Settings.addScore(lastScore);//保存分数Settings.save();}}

   这里我们每次碰到金币就会加上10分,到游戏结束后,将最终得分保存起来,同时更新排行榜。

Settings:

package com.zhf.mylibgdx;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import com.badlogic.gdx.Gdx;
/*** 设置类:三个方法: 1.load()读取声音开关和最高分.  2.save()保存配置     3.addScore()最高分排行榜,对数组赋值。* @author ZHF**/
public class Settings {//记录声音开起与关闭public static boolean soundEnabled = true;//默认分数排行榜分数public final static int[] highscores = new int[] {100, 80, 50, 30, 10};//保存的文件名public final static String file = ".superjumper";/**加载配置文件**/public static void load () {BufferedReader in = null;try {in = new BufferedReader(new InputStreamReader(Gdx.files.external(file).read()));soundEnabled = Boolean.parseBoolean(in.readLine());for (int i = 0; i < 5; i++) {highscores[i] = Integer.parseInt(in.readLine());}} catch (Exception e) {e.printStackTrace();} finally {try {if (in != null) in.close();} catch (IOException e) {}}}/**保存分值**/public static void save () {BufferedWriter out = null;try {//声音的开关out = new BufferedWriter(new OutputStreamWriter(Gdx.files.external(file).write(false)));out.write(Boolean.toString(soundEnabled));for (int i = 0; i < 5; i++) {//将分数写入文件out.write(Integer.toString(highscores[i]));}} catch (Exception e) {e.printStackTrace();} finally {try {if (out != null) out.close();} catch (IOException e) {}}}/**将所得分数与排行榜分数比较,从高到低重新排一下**/public static void addScore (int score) {for (int i = 0; i < 5; i++) {if (highscores[i] < score) {for (int j = 4; j > i; j--)highscores[j] = highscores[j - 1];highscores[i] = score;break;}}}
}

   再次运行代码,加了几个金币,分值发生变化了,回到主界面分数排行榜也发生变化了!(原先默认:100, 80, 50, 30, 10


接下来就是声音部分:


我们再次回到GameScreen中:

//实例化场景worldListener = new WorldListener() {@Overridepublic void jump () {Assets.playSound(Assets.jumpSound);}@Overridepublic void highJump () {Assets.playSound(Assets.highJumpSound);}@Overridepublic void hit () {Assets.playSound(Assets.hitSound);}@Overridepublic void coin () {Assets.playSound(Assets.coinSound);}};

   在监听器中给对应方法播放对应的声音,当然少不了在Asset中添加对声音资源的加载:

声明:

//声音部分public static Sound clickSound; //按下音效public static Music music;  //背景音乐public static Sound jumpSound; //跳跃public static Sound highJumpSound; //高跳public static Sound hitSound; //碰撞public static Sound coinSound;  //金币

实例化:

//背景音乐music = Gdx.audio.newMusic(Gdx.files.internal("data/music.mp3"));music.setLooping(true); //循环music.setVolume(0.5f);  //大小if (Settings.soundEnabled) music.play();jumpSound = Gdx.audio.newSound(Gdx.files.internal("data/jump.ogg"));highJumpSound = Gdx.audio.newSound(Gdx.files.internal("data/highjump.ogg"));hitSound = Gdx.audio.newSound(Gdx.files.internal("data/hit.ogg"));coinSound = Gdx.audio.newSound(Gdx.files.internal("data/coin.ogg"));//点击音效clickSound = Gdx.audio.newSound(Gdx.files.internal("data/click.ogg"));

ok!运行一下!貌似没有什么问题,对应的声音都播放出来了!


  到此为止,libgdx中demo程序superjumper分版本的学习就结束了,由于本人也是边学边总结,中间肯定有许多地方讲解的不完善,不妥的地方,这里先想大家说声抱歉哈,希望大家发现问题能及时提出来,这样我也能进步么!这里还是那句话,在学习新东西的时候,我们的不求甚解也不失为一种快速掌握的好方法! 希望这一些列学习笔记能帮助到初学者!

完整代码下载:http://down.51cto.com/data/897232  代码里详细注解哦!

转载于:https://blog.51cto.com/smallwoniu/1263957

libgdx游戏引擎开发笔记(十三)SuperJumper游戏例子的讲解(篇七)----各个物体的创建及其碰撞检测...相关推荐

  1. 简单游戏引擎开发笔记(一)

    ---恢复内容开始--- 一.游戏引擎简介 1.概念 游戏引擎是指一些已编写好的可编辑电脑游戏系统或者一些互交式实时图像应用程序的核心组件.这些系统为游戏设计者提供各种编写游戏所需的各种工具,其目的在 ...

  2. libgdx游戏引擎开发笔记(一)引擎介绍和Helloworld

       做Android快一年了,项目也做了四五个,感觉没什么动力向前,思绪整理了一段时间,决定转入Android游戏开发,同时发现了一款强大的游戏引擎libgdx,在此边学边整理,好记性不如烂笔头嘛! ...

  3. 纯c语言游戏引擎开发,C++ 写个游戏引擎—(基础篇) 1

    目标:用 c++ 写个游戏引擎打基础 基本要求:有一定编程基础,对游戏编程有热情 开发平台:windows 开发工具:visual studio 2017 communicty 前言 今天 C++ 视 ...

  4. C++原生游戏引擎开发棒子打老鼠游戏!

    VC++棒子打老鼠游戏源代码,俗称打地鼠,程序可以编译,但运行时候棒子的显示有些问题,也就是程序在处理BMP图像时候有些不完善,不过整体可以玩,相信大家都知道这款游戏 ,现在发布源代码供研究. 项目截 ...

  5. libgdx游戏引擎开发笔记(十)SuperJumper游戏例子的讲解(篇四)---- 主游戏界面内部框架编写...

    上一讲,我们已经实现了点击play进入游戏界面但仅仅是个黑屏  今天,我们就试着编写代码让它出现游戏的一些简单场景.还是在上一讲的代码基础上,我们创建两个类:World 和 WorldRenderer ...

  6. 【Cocos2d-x游戏引擎开发笔记(13)】Tiled Map Editor(一)

    原创文章,转载请注明出处:http://blog.csdn.net/zhy_cheng/article/details/8308609 Tiled Map Editor是Cocos2d-x支持的地图编 ...

  7. 游戏引擎开发和物理引擎_视频游戏开发的最佳游戏引擎

    游戏引擎开发和物理引擎 In this article, we'll look at some of the most popular game engines for video game deve ...

  8. 【Visual C++】游戏开发笔记二十 游戏基础物理建模(二) 重力系统的模拟

    本系列文章由zhmxy555(毛星云)编写,转载请注明出处. http://blog.csdn.net/zhmxy555/article/details/7496200 作者:毛星云    邮箱: h ...

  9. unity应用开发实战案例_Unity3D游戏引擎开发实战从入门到精通

    Unity3D游戏引擎开发实战从入门到精通(坦克大战项目实战.NGUI开发.GameObject) 一.Unity3D游戏引擎开发实战从入门到精通是怎么样的一门课程(介绍) 1.1.Unity3D游戏 ...

最新文章

  1. python web为什么不火-python web为什么不火
  2. linux安装和配置 mysql、redis 过程中遇到的问题记录(转)
  3. 计算机专业考研英语二国家线,历年考研英语国家线汇总(2009-2020)
  4. 浅谈移动Web开发:深入概念
  5. Spring-05 -AOP [面向切面编程] -Schema-based 实现aop的步骤
  6. 深挖android low memory killer
  7. 黄聪:解决wordpress定时发布文章失败”丢失计划任务”的插件
  8. (转) 分布式-微服务-集群的区别
  9. chattr 设置隐藏属性
  10. 简单的TCP回射服务
  11. 数据分析案例-基于随机森林算法探索影响人类预期寿命的因素并预测人类预期寿命
  12. 人民日报申论范文:“传统文化”怎么写?
  13. 2014腾讯实习生招聘数组墙算法
  14. 什么是盒子模型,盒子模型,标准盒模型,怪异盒模型,两种盒模型的区别,box-sizing属性
  15. yii 高级版后台清理前台的缓存
  16. DHCP V6 server配置
  17. 想在公众号上做一个测试软件,公众号测试新功能想要扭转乾坤?
  18. 目前企业的云计算转型,主要可以划分为哪四个阶段?
  19. systemverilog中rand机制的 $urandom_range()函数
  20. three.js 后期处理通道postprocessing

热门文章

  1. Android app 标签,android 获取APP的唯一标识applicationId的实例
  2. java6个人抽奖抽三个人,基于Java的抽奖逻辑
  3. syslog 向内存中缓存_动画:深入浅出从根上理解 HTTP 缓存机制及原理!
  4. PhP加载时显示动画,在ajax请求完之前的loading加载的动画效果实现
  5. python36中文手册_python36中文手册_python_36_文件操作4
  6. vision软件_Roboguide软件:高速拾取仿真工作站相机与工具添加与配置
  7. vscode使用sass_推荐7 个 极好用的VS Code 插件
  8. Java final 关键字简述
  9. C--数据结构--树的学习
  10. go为什么比php性能好,刚学 GO,撸了个支付宝发券的程序,为什么性能还比不上 PHP ?...