Kotlin 250 - Aiming the Missiles
GitHub Decentralized Repo
GitHub Centralized Repo
GitHub Flat Repo
I just punched in some code to aim the missiles. Let me share it with you.
I changed fireMissile
thus:
fun fireMissile() {
controls_fire = false
val missile: SpaceObject = availableShipMissile() ?: return
val offset = Vector2(50.0, 0.0).rotate(Ship.angle)
missile.x = offset.x + Ship.x
missile.y = offset.y + Ship.y
val velocity = Vector2(30.0, 0.0).rotate(Ship.angle)
missile.dx = velocity.x
missile.dy = velocity.y
missile.active = true
}
The first bit rotates the point (50,0) in the direction of the ship’s rotation. We set the missile location to that value plus the ship’s position, thus 50 out in front of the ship.
Then we take a velocity vector (30,0) and rotate that to the direction of aim and set the missile’s velocity to that. Now when we rotate the ship and fire, the missile heads off in the direction the ship is pointing:
So that’s nice. However, we should really add in the ship’s motion. I forgot to do that.
fun fireMissile() {
controls_fire = false
val missile: SpaceObject = availableShipMissile() ?: return
val offset = Vector2(50.0, 0.0).rotate(Ship.angle)
missile.x = offset.x + Ship.x
missile.y = offset.y + Ship.y
val velocity = Vector2(166.6, 0.0).rotate(Ship.angle)
missile.dx = velocity.x + Ship.dx
missile.dy = velocity.y + Ship.dy
missile.active = true
}
I changed the basic velocity to equal what’s used in the other versions. Now the missiles fly off faster if the ship is going faster.
So that’s nice. The code is still a bit raggedy. I think we should seriously consider converting our position and speed values to Vector2, just as one example. After all, it is a built-in type. And magic constants all over.
Raggedy code. Needs improvement. We will, I promise.