最近在做射击游戏,要求指定一个子弹发射位置,然后指定一个敌人位置,敌人位置可以在任何方向,之后子弹会向敌人方向射击,数学不太好,感觉应该有更聪明的办法,求指点,我的代码如下
这是子弹每帧x, y以及子弹角度计算代码
void StraightBulletScript::onBulletInit() {
// get enemy entity
this->_targetEntity = entity->getEntityByTag("enemy");
// get enemy position
Vec2 enemyPos = _targetEntity->getTransform()->getPosition();
// get bullet start position
Vec2 entityPos = transform->getPosition();
// compute the distance from enemy position to bullet start position
Vec2 dis = enemyPos - entityPos;
// x coordinate step per frame
stepDisX = 20;
// y coordinate step per frame
stepDisY = 20;
// the angle degree from bullet start position to enemy position based on x coordinate line
angle = -atan2(dis.y, dis.x) * 180 / 3.141592653;
// direction fix
if (dis.x < 0 && dis.y > 0 && (abs(dis.x) > abs(dis.y))) {
stepDisY = -stepDisY;
stepDisX = -stepDisX;
}
if (dis.x > 0 && dis.y < 0 && (abs(dis.x) < abs(dis.y))) {
stepDisY = -stepDisY;
stepDisX = -stepDisX;
}
if (dis.x < 0 && dis.y < 0) {
stepDisY = -stepDisY;
stepDisX = -stepDisX;
}
// compute the slope, and scale x or y
if (abs(dis.x) > abs(dis.y)) {
slope = dis.y / dis.x;
stepDisY *= slope;
} else {
slope = dis.x / dis.y;
stepDisX *= slope;
}
}
```
计算完子弹参数后,每帧调用如下代码更新
transform->setPositionX(transform->getPositionX() + stepDisX);
transform->setPositionY(transform->getPositionY() + stepDisY);
transform->setRotation(angle);
```