简体   繁体   English

将精灵移动到鼠标单击[Libgdx];

[英]Move sprite to mouse click [Libgdx];

I'm new to libgdx Game programming and I want to create an RPG kind of game. 我是libgdx游戏编程的新手,我想创建一个RPG类型的游戏。

I want to make the player move towards the mouse/touch position. 我想让玩家朝着鼠标/触摸位置移动。

I have calculated a logical way to do this, but it seems that the player moves only one frame at a time, which means that the player need to click several times to get to the right position, instead of walking to the click position frame by frame only by one click. 我已经计算出了这样做的合理方法,但似乎玩家一次只能移动一帧,这意味着玩家需要多次点击才能到达正确的位置,而不是走到点击位置框架框架只需点击一下即可。

My code: 我的代码:

Gdx.input.setInputProcessor(new Input(){
    public boolean touchDown(int screenX, int screenY, int pointer, int button) {
        projected = new Vector3(screenX, screenY, 0);
        cam.unproject(projected);

        if(projected.x != position.x || projected.y != position.y){
            float pathX = projected.x - position.x;
            float pathY = projected.y - position.y;

            float distance = (float) Math.sqrt(pathX * pathX + pathY * pathY);
            float directionX = pathX / distance;
            float directionY = pathY / distance;

            position.x += directionX * Speed;
            position.y += directionY * Speed;
        }

        return true;
    }

Your method is called (once) every time you touch the screen. 每次触摸屏幕时都会调用您的方法(一次)。 Your method changes the position (once) with 您的方法更改位置(一次)

position.x += directionX * Speed;
position.y += directionY * Speed;

So every touch of the screen only moves your Sprite once. 所以每次触摸屏幕只会移动你的精灵一次。

Your Screen class has a method render(float deltaTime) . Screen类有一个方法render(float deltaTime) This gets called repeatedly, with the argument giving the time since it was last called. 这会被重复调用,参数给出自上次调用以来的时间。 This makes it a useful method in which to do things you need to happen repeatedly (like update a sprite's position). 这使得它成为一种有用的方法,可以执行需要重复发生的事情(比如更新精灵的位置)。

So what you really want to do inside your touchDown() is to set your Sprite's direction (as a field contained in your Sprite object). 所以你真正想要在touchDown()是设置你的Sprite方向(作为Sprite对象中包含的字段)。 You can then write a method something like 然后你可以编写类似的方法

update(float deltaTime) {
   position.x += directionX * Speed * deltaTime;
   position.y += directionY * Speed * deltaTime;
}

inside your Sprite's class. 在你的精灵课程中。 This is almost what you wrote, but the * deltaTime ensures the amount the position changes by is only the distance that would have been covered since the previous call of this method. 这几乎就是你所写的,但* deltaTime确保位置改变的量只是自上次调用此方法以来所覆盖的距离。

This method still never gets called though, so you need to call it from your Screen.render(deltaTime) method: 此方法仍然永远不会被调用,因此您需要从Screen.render(deltaTime)方法调用它:

render(float deltaTime) {
   mySprite.update(deltaTime);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM