简体   繁体   English

单击Java直接射击对象libgdx

[英]Shooting object directly at click java libgdx

I am trying to get my player to shoot a spell and it travels to where ever the player clicked. 我正试图让我的玩家射击咒语,然后将其传播到该玩家点击的地方。 I can easily accomplish this by doing the following. 通过执行以下操作,我可以轻松完成此操作。

    if(position.x >= destination.x - 1 && position.x <= destination.x + 1)
        reachedX = true;
    if(position.y >= destination.y - 1 && position.y <= destination.y + 1)
        reachedY = true;

However if the players origin is at, for example, 0,0 and I click at 10,300 then it travels right and up but when the spell reaches an x of 10 it travels directly upwards. 但是,如果玩家原点位于0,0,而我单击10,300,则它向右上方移动,但是当咒语达到x的10时,它将直接向上移动。 I want the spell to travel at an angle that it will reach the x coordinate at the same time as the y coordinate. 我希望该咒语以一定的角度传播,使其与y坐标同时到达x坐标。 Here is an image showing what happens and what I want to happen. 这是一张图像,显示发生了什么以及我想发生什么。

图片范例

In the first picture it looks like the spell goes 45° until it reaches the right x-coordinate. 在第一张图片中,该咒语看起来像是45°旋转,直到到达正确的x坐标为止。 This sounds like the x and y speed are equals, no matter where the destination point is. 听起来无论目的地在哪里,x和y速度都相等。
You shuld instead have a direction and depending on that ax and y speed. 相反,您应该有一个方向,并取决于该轴和y的速度。
For that you first need to get the point, the player is clicking. 为此,您首先需要弄清楚要点,玩家点击即可。
Therefore you can implement InputProcessor and it's touchDown(int screenX, int screenY, int pointer, int button) . 因此,您可以实现InputProcessor及其touchDown(int screenX, int screenY, int pointer, int button)
The screenX and screenY arguments are given in screen coordinates (pixels) and therefore need to be converted to your world-coordinates. screenXscreenY参数以屏幕坐标(像素)给出,因此需要转换为您的世界坐标。 This can be done using the camera or the viewport and it's unproject(Vector2 screenCoords) . 这可以使用cameraviewport来完成,并且它是unproject(Vector2 screenCoords) This method returns a Vector2 giving the world-coordinates. 此方法返回给出世界坐标的Vector2
Now you need to find out the direction Vector2 between you and the clicked point. 现在,您需要找出您和单击的点之间的方向Vector2 The direction Vector is calculated like this: 方向Vector的计算如下:

new Vector2(otherPos.x - myPos.x, otherPos.y - myPos.y).nor();

This returns the normalized direction Vector between the two points. 这将返回两点之间的归一化方向Vector
Now you only need to move the spell by dir.x*spellSpeed*delta in x-direction and dir.y*spellSpeed*delta in y-direction and it should look like in your second picture. 现在,您只需要在x方向上移动dir.y*spellSpeed*delta在y方向上移动dir.x*spellSpeed*delta ,该咒语应类似于第二张图片。

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

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