如何使用libgdx将3d模型移动到触摸点?

时间:2017-04-21 15:20:20

标签: android libgdx

模型不会移动到触摸点,而是移动到右下角的某个位置。我已经使用unproject将屏幕点映射到世界空间点,我不知道为什么翻译不正确。你们有什么想法吗?谢谢!

package com.mygdx.game;

import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.PerspectiveCamera;
import com.badlogic.gdx.graphics.g3d.Environment;
import com.badlogic.gdx.graphics.g3d.Model;
import com.badlogic.gdx.graphics.g3d.ModelBatch;
import com.badlogic.gdx.graphics.g3d.ModelInstance;
import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute;
import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.utils.Array;

public class Basic3DTest implements ApplicationListener {
  public PerspectiveCamera cam;
  public ModelBatch modelBatch;
  public AssetManager assets;
  public Array<ModelInstance> instances = new Array<ModelInstance>();
  public Environment environment;
  public boolean loading;
  private ModelInstance shipInstance;
  private Model ship;

  @Override
  public void create () {
    modelBatch = new ModelBatch();
    environment = new Environment();
    environment.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.4f, 0.4f, 0.4f, 1f));
    environment.add(new DirectionalLight().set(0.8f, 0.8f, 0.8f, -1f, -0.8f, -0.2f));

    cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
    cam.position.set(7f, 7f, 7f);
    cam.lookAt(0,0,0);
    cam.near = 1f;
    cam.far = 300f;
    cam.update();

    assets = new AssetManager();
    assets.load("data/ship.g3db", Model.class);
    loading = true;
  }

  private void doneLoading() {
    ship = assets.get("data/ship.g3db", Model.class);
    shipInstance = new ModelInstance(ship);
    instances.add(shipInstance);
    loading = false;
  }

  @Override
  public void render () {
    if (loading && assets.update())
      doneLoading();

    Gdx.gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);

    modelBatch.begin(cam);
    modelBatch.render(instances, environment);
    modelBatch.end();

    if (Gdx.input.isTouched()) {
      Vector3 point = cam.unproject(new Vector3(Gdx.input.getX(), Gdx.input.getY(), 0));
      shipInstance.transform.idt().translate(point.x, point.y, 0);
    }
  }

  @Override
  public void dispose () {
    modelBatch.dispose();
    instances.clear();
    assets.dispose();
  }

  @Override
  public void resize(int width, int height) {
  }

  @Override
  public void pause() {
  }

  @Override
  public void resume() {
  }
}

result I want want

修改

if (Gdx.input.isTouched()) {
  Ray ray = cam.getPickRay(Gdx.input.getX(), Gdx.input.getY());
  position.set(ray.direction).add(ray.origin);
  shipInstance.transform.setTranslation(position);
}

0 个答案:

没有答案