简体   繁体   English

将对象移向点android

[英]Moving an object towards a point android

I have this in the initialization of a bullet object: 我在子弹对象的初始化中有这个:

    x = startX;
    y = startY;
    double distance = Math.sqrt(((endX - x) ^ 2) + ((endY - y) ^ 2));
    speedX = (6 * (endX - x)) / distance;
    speedY = (6 * (endY - y)) / distance;

It goes to where I touch on the screen, but the further away I touch, the faster it goes. 它会移动到我在屏幕上触摸的位置,但是我触摸得越远,它就越快。 This works fine on paper, I've tried it with different lengths and it should work, but bullets need to move 6 pixels on the line from the player to the point touched every step. 这在纸上工作得很好,我尝试了不同的长度它应该工作,但是子弹需要在玩家的线上移动6个像素到每一步触摸的点。 And its update method moves of course. 它的更新方法当然也在移动。 But why do bullets move at different speeds? 但为什么子弹以不同的速度移动?

If I remember my Java operators... 如果我记得我的Java运营商......

Replace 更换

double distance = Math.sqrt(((endX - x) ^ 2) + ((endY - y) ^ 2));

with

double distance = Math.sqrt(Math.pow(endX - x, 2) + Math.pow(endY - y, 2));

Assuming that all measurements are in pixels and you want the speed to be 6 pixels per step, then you can calculate the velocity by using a little bit of trig: 假设所有测量都以像素为单位,并且您希望速度为每步6像素,那么您可以使用一点点trig来计算速度:

double theta = Math.atan2(endY - startY, endX - startX);
velX = 6 * Math.cos(theta);
velY = 6 * Math.sin(theta);

Note that I am using the terms "speed" and "velocity" as a physicist would; 请注意,我正在使用术语“速度”和“速度”作为物理学家; speed is a scalar value and velocity is a vector with magnitude and direction. 速度是标量值,速度是具有幅度和方向的矢量。

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

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