【发布时间】:2010-11-04 21:50:59
【问题描述】:
我正在开发一款使用射弹的游戏。所以我创建了一个 Projectile 类,并在用户触摸屏幕时创建了一个新实例:
@Override
public boolean onTouch(View v, MotionEvent e){
float touch_x = e.getX();
float touch_y = e.getY();
new Projectile(touch_x, touch_y);
}
还有 Projectile 类:
public class Projectile{
float target_x;
float target_y;
Path line;
public Projectile(float x, float y){
target_x = x;
target_y = y;
line = new Path();
line.moveTo(MyGame.mPlayerXPos, MyGame.mPlayerYPos);
line.lineTo(target_x, target_y);
}
}
这样就形成了一个包含 2 点、玩家位置和触摸坐标的路径。我的问题是 - 你如何访问这条线上的点?例如,如果我想在直线的半点处获取 Projectile 的 x,y 坐标,或者 Projectile 在 100 个刻度后(以 X 像素/刻度的速度移动)的点?
我还需要 Projectile 在到达终点后继续移动。我需要使用 line.addPath(line) 来继续扩展路径吗?
编辑
我设法让射弹沿直线移动,但它们朝奇怪的方向移动。我不得不捏造一些代码:
private void moveProjectiles(){
ListIterator<Projectile> it = Registry.proj.listIterator();
while ( it.hasNext() ){
Projectile p = it.next();
p.TimeAlive++;
double dist = p.TimeAlive * p.Speed;
float dx = (float) (Math.cos(p.Angle) * dist);
float dy = (float) (Math.sin(p.Angle) * dist);
p.xPos += dx;
p.yPos += -dy;
}
}
Angle 一定是问题所在。我正在使用这种方法,效果很好:
private double getDegreesFromTouchEvent(float x, float y){
double delta_x = x - mCanvasWidth/2;
double delta_y = mCanvasHeight/2 - y;
double radians = Math.atan2(delta_y, delta_x);
return Math.toDegrees(radians);
}
但是,对于屏幕中心上方的触摸,它返回 0-180,对于下方的触摸,它返回 0 到 -180。这是个问题吗?
【问题讨论】:
-
我敢打赌,您正在使用左手坐标系——屏幕左上角的 (0,0)。大多数三角函数采用右手坐标系——屏幕左下角的 (0,0)。如果您使用我的解决方案,您选择哪个坐标系都没有关系。
标签: android path coordinate-systems