CreateJS Canvas中外星对象触底后无法转向移动的代码层面原因咨询
Let's break down the exact code logic causing this behavior—your core issue comes down to imprecise position matching and how your conditional checks interact with the step size of your movement:
1. The Problem with object.y Values
Your drop() function moves the alien down by 3 pixels each tick, starting from object.y = 1. That means object.y will always be a value like 1, 4, 7, 10, ...—mathematically, 1 + 3n where n is an integer.
When your canvas height is 150, there's no integer n that makes 1 + 3n = 150 (150 - 1 = 149, which isn't divisible by 3). So object.y will never exactly equal can.height. Instead, it will jump from 148 (1 + 3×49) straight to 151 in one tick—skipping right past 150 entirely.
2. Conditional Checks Fail After Overstepping
Once object.y = 151:
- The
drop()function's conditionobject.y < can.heightis now false (151 > 150), sodrop()stops running. - The
bottom()function has two conditions:object.y == can.height(false, since 151 ≠ 150) andspeedY == -5(false, sincespeedYis still 5 from initialization). Neither condition is met, sobottom()does nothing. - In every subsequent tick, neither function's conditions are satisfied. No code modifies
object.yorspeedYanymore, so the alien just stops.
3. Why It Works When Canvas Height is 100
When you set the canvas height to 100, 1 + 3n = 100 has a valid integer solution: n = 33 (1 + 3×33 = 100). Here's what happens:
- When
object.yhits exactly 100,drop()stops becauseobject.y < 100is false. - The
bottom()function's first conditionobject.y == can.heightis true, so it setsspeedY = -5and moves the alien up 3 pixels to 97. - In the next tick,
bottom()'s second conditionspeedY == -5is true, so it continues moving the alien up—exactly as you expected.
Where Your Expected Logic Was Off
You assumed the alien would reach object.y == can.height exactly, but your movement step size (3 pixels) and starting position (1 pixel) mean this only happens when can.height - 1 is divisible by 3. For any other height, the alien overshoots the bottom, and your bottom() function never gets triggered to reverse direction.
内容的提问来源于stack exchange,提问作者William Garske

