You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CreateJS Canvas中外星对象触底后无法转向移动的代码层面原因咨询

Why Your Alien Stops Instead of Reversing After Hitting the Bottom

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 condition object.y < can.height is now false (151 > 150), so drop() stops running.
  • The bottom() function has two conditions: object.y == can.height (false, since 151 ≠ 150) and speedY == -5 (false, since speedY is still 5 from initialization). Neither condition is met, so bottom() does nothing.
  • In every subsequent tick, neither function's conditions are satisfied. No code modifies object.y or speedY anymore, 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.y hits exactly 100, drop() stops because object.y < 100 is false.
  • The bottom() function's first condition object.y == can.height is true, so it sets speedY = -5 and moves the alien up 3 pixels to 97.
  • In the next tick, bottom()'s second condition speedY == -5 is 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 19:27:44