libGDX游戏开发之运动轨迹绘制(十一)
libGDX系列 ,游戏开发有unity3D巴拉巴拉的,为啥还用java开发?因为我是Java程序员emm…国内用libgdx比较少,多数情况需要去官网和google找资料,相互学习的可以加我联系方式。
按轨迹移动的绘制需要用到数学函数,通过不断变动x,y坐标达到效果
1、圆形轨迹移动
经典:按圆形轨迹移动,回顾一下正弦和余弦: 当给定固定左边时是这样的: 我们看到A点的坐标可以根据 θ 角度正弦余弦求出,渲染中通过变化 θ 达到圆形运动,实现代码如下:
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
public class RunTest extends ApplicationAdapter {
private Texture texture;
private SpriteBatch batch;
private float R = 100;
private float originX = 200, originY = 200;
private float Pi = 3.1416f;
private float angle = 1f;
@Override
public void create() {
batch = new SpriteBatch();
texture = new Texture(Gdx.files.internal("plane/player1.png"));
}
@Override
public void render() {
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
float a = 2 * Pi / 360 * angle;
float x = originX + (float) Math.sin(a) * R;
float y = originY + (float) Math.cos(a) * R;
if (++angle > 360f) {
angle = 1f;
}
batch.begin();
batch.draw(texture, x, y);
batch.end();
}
}
效果如下: 不清除屏幕效果如下:
2、按正弦轨迹移动
正弦函数如下:
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
public class RunTest02 extends ApplicationAdapter {
private Texture texture;
private SpriteBatch batch;
private float originX = 0, originY = 200;
private float Pi = 3.1416f;
private float angle = 0f;
private float r = 100;
@Override
public void create() {
batch = new SpriteBatch();
texture = new Texture(Gdx.files.internal("plane/player1.png"));
}
@Override
public void render() {
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
if (++originX > 648) {
originX = 0;
}
float a = 2 * Pi / 360 * angle;
float y = originY + (float) Math.sin(a) * r;
if (++angle > 360f) {
angle = 0f;
}
batch.begin();
batch.draw(texture, originX, y);
batch.end();
}
}
效果如下: 不清除屏幕效果:
|