用距离检查物体之间的碰撞
-
预备知识
介绍
我们经常需要检查两个物体是不是正在触碰彼此。举个例子,如果一个角色碰到了盒子,我们可以让角色坐在盒子上。
https://cdncreaticodecom.b-cdn.net/scratch-gui-projects/forum/150ca728-7136-459b-ac95-1df70211a882.gif" width="400" style="border-radius: 5px; border: 1px solid #29622d;">
检查两个物体是否正在触碰彼此的最简单方法就是检查他们之间的距离。
利用X和Y位置来计算距离
当两个物体都在平地上时,我们只需要使用X和Y位置来检查它们之间的距离:
https://cdncreaticodecom.b-cdn.net/scratch-gui-projects/forum/bbe4ff5e-ce13-492c-a2af-f123a55f2fc8.png" width="800" style="">
举个例子,角色和盒子之间的直线二维距离被展示在下图中:
https://cdncreaticodecom.b-cdn.net/scratch-gui-projects/forum/62914e68-2b7a-4a31-9df9-c72c58cd0976.png" width="700" style="border-radius: 5px; border: 1px solid #29622d;">
演示程序
在这个程序例子中,我们把一个盒子放在Y=100的位置。
https://cdncreaticodecom.b-cdn.net/scratch-gui-projects/forum/5d100887-4836-46e2-91fc-98db469a624d.png" width="900" style="">
接着,每次我们点击”w“键时,我们都把角色向前移一下:
https://cdncreaticodecom.b-cdn.net/scratch-gui-projects/forum/35a9871e-1e8d-4360-bbcd-789f0313b6d5.png" width="900" style="">
动手时刻:
https://play.creaticode.com/projects/836c92f886f791086cf57b1c
使用三维距离
有时候,二维距离并不足够准确。举个例子,假设一个物体漂浮在空中,而角色处于物体下方。两者之间的二位距离很接近0,但是他们并没有接触到彼此。要把垂直的距离纳入考量,我们需要计算三维距离:
https://cdncreaticodecom.b-cdn.net/scratch-gui-projects/forum/282254b2-e1a7-438c-9173-1f11e0342a07.png" width="300" style="border-radius: 5px; border: 1px solid #29622d;">
演示程序
在这个程序例子中,我们把一个盒子放在Z=140的位置,然后我们把角色移到她和盒子之间的三维距离少过110的位置。
https://cdncreaticodecom.b-cdn.net/scratch-gui-projects/forum/d9661991-b89f-428d-936a-2b754d6c84fb.gif" width="300" style="border-radius: 5px; border: 1px solid #29622d;">
https://cdncreaticodecom.b-cdn.net/scratch-gui-projects/forum/fee24fb0-4c38-47a7-908f-1ad688d49314.png" width="900" style="border-radius: 5px; border: 1px solid #29622d;">
动手时刻:
https://play.creaticode.com/projects/32f4e2bffc79c532fbeba129
-
I CreatiCode pinned this topic on
Hello! It looks like you're interested in this conversation, but you don't have an account yet.
Getting fed up of having to scroll through the same posts each visit? When you register for an account, you'll always come back to exactly where you were before, and choose to be notified of new replies (either via email, or push notification). You'll also be able to save bookmarks and upvote posts to show your appreciation to other community members.
With your input, this post could be even better 💗
Register Login