5. Use Libgdx to design a simple game ------ raindrops, libgdx ------

Source: Internet
Author: User
Tags gety libgdx

5. Use Libgdx to design a simple game ------ raindrops, libgdx ------

(Original: http://www.libgdx.cn/topic/49/5-%E4%BD%BF%E7%94%A8libgdx%E8% AE %BE%E8% AE %A1%E4%B8%80%E4%B8%AA%E7% AE %80%E5%8D%95%E7%9A%84%E6%B8%B8%E6%88%8F-%E9%9B%A8%E6%BB%B4)

Before in-depth research on the APIS provided by Libgdx, we should first create a simple game to feel the functions of libgdx. Here we will briefly introduce some features.

Technologies used:

  • File Access

  • Clear Screen

  • Rendering Image

  • Use a camera

  • Basic Input

  • Playing Sound Effects

Project Settings
First, create a libgdx project and click here.

  • Application name: drop

  • Package name: cn. libgdx. drop

  • Game class: Drop

After the project is generated, import it to eclipse (remember that it is a Gradle project ).

Game Design Ideas
The game idea is simple:

  • Use a bucket of raindrops

  • Bucket at the bottom of the screen

  • Raindrops are randomly downloaded from the top of the screen to accelerate falling

  • Players can drag buckets horizontally

  • The game is not over

Assets File

Click to download the resource file

We need images and sound effects to make the game better. For images, we need to set the resolution to 800*480 pixels (in Android, we need to set it to landscape )). If the device does not have this resolution, we need to set the applicable screen.
To make resource files available in the game, we must put the resource files in the assets folder of the Android project. There are four files in total: drop.wav,rain.mp3,droplet.pngand bucket.png. Put them in the drop-android/assets/folder.

Configure the startup class
After preparing the previous configuration, we need to modify the startup class of the desktop project. Open the export toplauncher. java file under the drop-desktop project. We need to set the window to 800*480 and the window title to "raindrops ". The Code is as follows:

Package cn. libgdx. drop. desktop;

Import com. badlogic. gdx. backends. lwjgl. LwjglApplication;
Import com. badlogic. gdx. backends. lwjgl. LwjglApplicationConfiguration;
Import cn. libgdx. drop. Drop;

Public class extends toplauncher {
Public static void main (String [] arg ){
LwjglApplicationConfiguration config = new LwjglApplicationConfiguration ();
Config. title = "raindrops ";
Config. width = 800;
Config. height = 480;
New LwjglApplication (new Drop (), config );
}
}

Find the Android Project (drop-android) and set the screen direction of the application. Therefore, you need to modify the AndroidManifest. xml file in the project root directory and set android: screenOrientation = "landscape ". The Code is as follows:

<? Xml version = "1.0" encoding = "UTF-8"?>
<Manifest xmlns: android = & quot; http://schemas.android.com/apk/res/android&quot;
Package = "cn. libgdx. drop. android"
Android: versionCode = "1"
Android: versionName = & quot; 1.0 & quot;>

<Uses-sdk android: minSdkVersion = "8" android: targetSdkVersion = "21"/>

<Application
Android: allowBackup = "true"
Android: icon = "@ drawable/ic_launcher"
Android: label = "@ string/app_name"
Android: theme = "@ style/GdxTheme">
<Activity
Android: name = & quot; cn. libgdx. drop. android. AndroidLauncher & quot;
Android: label = "@ string/app_name"
Android: screenOrientation = "landscape"
Android: configChanges = "keyboard | keyboardHidden | orientation | screenSize">
<Intent-filter>
<Action android: name = & quot; android. intent. action. MAIN & quot;/>
<Category android: name = & quot; android. intent. category. LAUNCHER & quot;/>
</Intent-filter>
</Activity>
</Application>

</Manifest>

Android: screenOrientation, a project generated using GDX-setup, is set to landscape by default.
Next, you need to disable the accelerometer and compass. This requires modifying the AndroidLauncher. java file of the Android project. The Code is as follows:
Package cn. libgdx. drop. android;

Import android. OS. Bundle;

Import com. badlogic. gdx. Gdx;
Import com. badlogic. gdx. backends. android. AndroidApplication;
Import com. badlogic. gdx. backends. android. AndroidApplicationConfiguration;

Import cn. libgdx. drop. Drop;

Public class AndroidLauncher extends AndroidApplication {
@ Override
Protected void onCreate (Bundle savedInstanceState ){
Super. onCreate (savedInstanceState );
AndroidApplicationConfiguration config = new AndroidApplicationConfiguration ();
Config. useAccelerometer = false;
Config. useCompass = false;
Initialize (new Drop (), config );
}
}

We cannot define the Activity resolution, which is determined by the Android operating system. As we have previously defined, set the resolution of all platforms to 800*480.

Start Coding

Now we divide the code into several parts for analysis. To maintain the portability of the project, we need to write the code to the core project.

Load Assets
Our first task is to load the assets file and save parameters. Assets are usually loaded in the ApplicationListener. create () method. The Code is as follows:

Package cn. libgdx. drop;

Import com. badlogic. gdx. ApplicationAdapter;
Import com. badlogic. gdx. Gdx;
Import com. badlogic. gdx. audio. Music;
Import com. badlogic. gdx. audio. Sound;
Import com. badlogic. gdx. graphics. GL20http: // com. badlogic. gdx. graphics. GL200;
Import com. badlogic. gdx. graphics. Texturehttp: // com. badlogic. gdx. graphics. Texturee;
Import com. badlogic. gdx. graphics. g2d. SpriteBatchhttp: // com. badlogic. gdx. graphics. g2d. SpriteBatchh;

Public class Drop extends ApplicationAdapter {
Private Texture dropImage;
Private Texture bucketImage;
Private Sound dropSound;
Private Music rainMusic;

@ Override
Public void create (){
// Load the resource into the GPU.
DropImage = new Texture (Gdx. files. internal ("droplet.png "));
BucketImage = new Texture (Gdx. files. internal ("bucket.png "));
// Load the raindrops sound and background music
DropSound = Gdx. audio. newSound (Gdx. files. internal ("drop.wav "));
RainMusic = Gdx. audio. newMusic (Gdx. files. internal ("rainaudio "));
// Start playing background music
RainMusic. setLooping (true );
RainMusic. play ();
}

@ Override
Public void render (){

}
}

Load the raindrops and buckets in the first two rows of the create () method. Texture is used to load an image and save it to the cache. Texture uses a file handle (FileHandle ). FileHandle is obtained through Gdx. files. Here there are different files. If you are calling Resources in the assets folder under Android, use internal.
Next, load the sound effects and background music. Libgdx divides sound effects and music. Sound effects are stored in the memory, and music is directly loaded from the saved place. Generally, music files are relatively large and cannot all be loaded into memory. If the sound is less than 10 seconds, it is best to use the sound. If the sound is more than 10 seconds, use the music.
The Gdx. audio. newSound () method is used to load audio. The Gdx. audio. newMusic () method is used to load music. Both methods need to pass a file handle (FileHandle), on the line above Texture.
The next step is to play the music and set the loop. If you run the program, it will rain.

Camera and SpriteBatch
Create a camera (camera) and a SpriteBatch. The purpose of using the camera is to use a 800*480 resolution on all platforms, regardless of its real screen size. SpriteBatch is a special class for drawing 2D images, similar to texture.
We add two variables to the class as follows:

Private OrthographicCamera camera;
Private SpriteBatch batch;
Add the following statement to the create () method to create camera:

Camera = new OrthographicCamera ();
Camera. setToOrtho (false, 800,480 );

This ensures that camera always shows the range of 800*480. It can be regarded as a virtual window. This enhances the portability of applications.
Next, create SpriteBatch in the create () method:
Batch = new SpriteBatch ();

Add Bucket
Finally, add buckets and raindrops. They need the following conditions:

  • The bucket and raindrops need a location information in 800*480.

  • The bucket and raindrops need width and height.

  • Texture

To display buckets and raindrops, we need to save their positions and sizes. You can use Rectangle in Libgdx. The Code is as follows:
Private Rectangle bucket;

In the create () method, we need to instantiate and set its only. It is set at the bottom of the screen and centered horizontally. The Code is as follows:

Bucket = new Rectangle ();
Bucket. x = 800/2-64/2;
Bucket. y = 20;
Bucket. width = 64;
Bucket. height = 64;

Note that in libgdx, the coordinate system origin is in the lower left corner.

Rendering Bucket

Next we need to render our bucket. First we need to set the screen background color and add the following code in the render () method:

@ Override
Public void render (){
Gdx. gl. glClearColor (0, 0, 0.2f, 1) http://Gdx.gl.glClearColor (0.2f, 1 );
Gdx. gl. glClear (gl1_gl _ COLOR_BUFFER_BIT) http://Gdx.gl.glClear (gl1_gl _ COLOR_BUFFER_BIT)

}
To use top-level classes, such as Texture and SpriteBatch. First, clear the screen and set it to blue. The first sentence indicates setting the screen color, and the second sentence indicates performing the Screen Cleaning operation.
Next we need to tell camera to make sure it is updated. Next, we set camera to be updated in each frame.

Next we need to render the bucket.
Batch. setProjectionMatrix (camera. combined );
Batch. begin ();
Batch. draw (bucketImage, bucket. x, bucket. y );
Batch. end ();

The first sentence sets the batch coordinate system as the camera, batch. end (); will submit our draw request immediately.

Move buckets

Next we control the bucket. When designing a game, we imagine that the bucket can be dragged. If you touch the screen or mouse button. We want to move the bucket horizontally.

If (Gdx. input. isTouched ()){
TouchPos = new Vector3 ();
TouchPos. set (Gdx. input. getX (), Gdx. input. getY (), 0 );
Camera. unproject (touchPos );
Bucket. x = touchPos. x-64/2;
}
First, we ask the input module to determine whether the input is touched by Gdx. input. isTouched. Next, we will pass the guardian who touched or clicked the mouse to the coordinate system of camera. The Gdx. input. getX () and Gdx. input. getY () methods are used to return the current touch and mouse position. To convert the current coordinate system to a coordinate system of camera, we need to use the camera. uproject () method. To call this method, we need a Vector3 and a three-dimensional vector. We create this vector, set the current coordinates of the current touch or mouse, and call the method.
It should be noted that touchPos needs to be declared in the class. if the if statement creates a variable every time it is executed, this will cause Android garbage processing to generate an exception.
TouchPos is a three-dimensional vector. You may want to know why we need a three-dimensional vector on a 2D interface. In fact, OrthographicCamera is a three-dimensional camera (camera ).

Move the bucket (keyboard)

In the desktop and browser environments, we also need to obtain keyboard input. Let's use the keyboard to operate the bucket through settings.
If (Gdx. input. isKeyPressed (Keys. LEFT) bucket. x-= 200 * Gdx. graphics. getDeltaTime () http://Gdx.graphics.getDeltaTime () FT) bucket. x-= 200 * Gdx. graphics. getDeltaTime ();
If (Gdx. input. isKeyPressed (Keys. RIGHT) bucket. x ++ = 200 * Gdx. graphics. getDeltaTime () http://Gdx.graphics.getDeltaTime () GHT) bucket. x ++ = 200 * Gdx. graphics. getDeltaTime ();

When the keyboard is pressed, The Gdx. input. isKeyPressed () method is used to determine whether a specified button is used. Gdx. graphics. getDeltaTime () returns a frame of time http://Gdx.graphics.getDeltaTime () to determine whether a specified button is used. Gdx. graphics. getDeltaTime () returns the time of a frame.
We also need to set the bucket not to cross-border:
If (bucket. x <0) bucket. x = 0;
If (bucket. x> 800-64) bucket. x = 800-64;

Add raindrops

For raindrops, we need to use a Rectangle array to store the positions and sizes of raindrops. Let's add a variable:
Private Array <Rectangle> raindrops;
This Array class is a tool class of libgdx, used to replace the ArrayList of java. The latter will generate garbage in many cases. Array to minimize the generation of garbage.
We also need to record the time of the last falling raindrops, So we add:
Private long lastDropTime;
We will store nanoseconds, which is why we use long.

The following method is used to randomly generate rain points:

Private void spawnRaindrop (){
Rectangle raindrop = new Rectangle ();
Raindrop. x = MathUtils. random (0,800-64 );
Raindrop. y = 480;
Raindrop. width = 64;
Raindrop. height = 64;
Raindrops. add (raindrop );
LastDropTime = TimeUtils. nanoTime ();
}

We need to instantiate in the create () method:
Raindrops = new Array <Rectangle> ();
SpawnRaindrop ();
Next we need to detect the interval of rain points in the render () method and generate a new rain point:
If (TimeUtils. nanoTime ()-lastDropTime> 1000000000) spawnRaindrop ();
We also need to move the rain. Here is the code:

Iterator <Rectangle> iter = raindrops. iterator ();
While (iter. hasNext ()){
Rectangle raindrop = iter. next ();
Raindrop. y-= 200 * Gdx. graphics. getDeltaTime () http://Gdx.graphics.getDeltaTime () getDeltaTime ();
If (raindrop. y + 64 <0) iter. remove ();
}
The rain points need to be rendered, so SpriteBatch is required for rendering:
Batch. begin ();
Batch. draw (bucketImage, bucket. x, bucket. y );
For (Rectangle raindrop: raindrops ){
Batch. draw (dropImage, raindrop. x, raindrop. y );
}
Batch. end ();

Finally, you need to determine whether the raindrops overlap with the bucket. If they overlap, delete the raindrops:

If (raindrop. overlaps (bucket )){
DropSound. play ();
Iter. remove ();
}

Exit cleanup
Finally, it needs to be cleared. The Code is as follows:
@ Override
Public void dispose (){
DropImage. dispose ();
BucketImage. dispose ();
DropSound. dispose ();
RainMusic. dispose ();
Batch. dispose ();
}

Click to download source code
(Www.libgdx.cn is copyrighted. If you need to reprint it, indicate the source)


How to make a static image dynamic? For example, fallen leaves and raindrops

Ulead GIF Animator V5.05 uses this software. It is easy to use. The principle is to connect multiple images into an animation and save them as GIF animated images. 100 times simpler than photoshop. you can make your own personalized QQ expressions. for example, for dynamic "hello", enter "you" in the first frame, add "good" in the second frame, and add "ah" in the third frame, the saved GIF image is dynamic. This is simple and can be done by moving words. You can add a lot of ideas. You can also import videos to make video images without sound. : Www.crsky.com/soft/4010.html download through the dedicated channel of thunder. If you want to make it flash, you can first put the first frame on your photo, and the second frame is a blank frame. You can also set the first and second frames as the photos, and the third frame as the blank ones, depending on your preferences. You can also use it to save the image as a GIF to modify the existing flash image. After downloading it, decompress it without installation. Use Ulead GIF Animator 5.exe to click the "file" menu and select the second item, open the image, open your photo, click the "frame" menu, select, add a frame, add a blank frame, and then click the "file" menu, select "Save as" and "GIF File". A simple flash image is finished. You can design other effects on your own. If this is too troublesome, you can make it online. It is simpler to create a website online: www.conew.com/...op.com All Rights Reserved. Copy is shameful!

Software can extract a part of music. For example, how can I extract a raindrops from a music?

You have a lot of audio editing software on Baidu, But I think MP3 Splitter is the easiest and best operation.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.