• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*******************************************************************************
2  * Copyright 2011 See AUTHORS file.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  ******************************************************************************/
16 
17 package com.badlogic.gdx.tests.examples;
18 
19 import com.badlogic.gdx.Gdx;
20 import com.badlogic.gdx.graphics.GL20;
21 import com.badlogic.gdx.graphics.OrthographicCamera;
22 import com.badlogic.gdx.graphics.Texture;
23 import com.badlogic.gdx.graphics.g2d.SpriteBatch;
24 import com.badlogic.gdx.math.Vector3;
25 import com.badlogic.gdx.tests.utils.GdxTest;
26 
27 /** Demonstrates how to let a sprite follow a finger touching the screen.
28  *
29  * @author mzechner */
30 public class MoveSpriteExample extends GdxTest {
31 	Texture texture;
32 	SpriteBatch batch;
33 	OrthographicCamera camera;
34 	Vector3 spritePosition = new Vector3();
35 
create()36 	public void create () {
37 		// create a SpriteBatch with which to render the sprite
38 		batch = new SpriteBatch();
39 
40 		// load the sprite's texture. note: usually you have more than
41 		// one sprite in a texture, see {@see TextureAtlas} and {@see TextureRegion}.
42 		texture = new Texture(Gdx.files.internal("data/bobargb8888-32x32.png"));
43 
44 		// create an {@link OrthographicCamera} which is used to transform
45 		// touch coordinates to world coordinates.
46 		camera = new OrthographicCamera();
47 
48 		// we want the camera to setup a viewport with pixels as units, with the
49 		// y-axis pointing upwards. The origin will be in the lower left corner
50 		// of the screen.
51 		camera.setToOrtho(false);
52 	}
53 
render()54 	public void render () {
55 		// set the clear color and clear the screen.
56 		Gdx.gl.glClearColor(1, 1, 1, 1);
57 		Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
58 
59 		// draw the sprite
60 		batch.begin();
61 		batch.draw(texture, spritePosition.x, spritePosition.y);
62 		batch.end();
63 
64 		// if a finger is down, set the sprite's x/y coordinate.
65 		if (Gdx.input.isTouched()) {
66 			// the unproject method takes a Vector3 in window coordinates (origin in
67 			// upper left corner, y-axis pointing down) and transforms it to world
68 			// coordinates.
69 			camera.unproject(spritePosition.set(Gdx.input.getX(), Gdx.input.getY(), 0));
70 		}
71 	}
72 }
73