栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

libGDX游戏开发之按轨迹移动(十一)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

libGDX游戏开发之按轨迹移动(十一)

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; // π 这里我们不用双精度,3.1416够了  PI = 3.14159265358979323846 ....
    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); // 清除屏幕

        //正弦函数 sinθ=y/r  角度 π不需要太过精确
        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; // π 这里我们不用双精度,3.1416够了  PI = 3.14159265358979323846 ....
    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; // r 为顶峰幅度值
        // 角度增加
        if (++angle > 360f) {
            angle = 0f;
        }
        // 绘制
        batch.begin();
        batch.draw(texture, originX, y);
        batch.end();
    }
}

效果如下:

不清除屏幕效果:

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/337129.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号