สร้างโลกของคุณเอง
การเขียนสคริปต์
Raycast
3min
ฟังก์ชัน raycast สามารถใช้ในการค้นหา object ภายในฉากใน unity ได้อย่างมีประสิทธิภาพ raycast ในการเขียนโปรแกรม unity เป็นประเภทของลำแสงเลเซอร์ ซึ่งจะยิงจากตำแหน่งในฉากและยิงจนกระทั่งมันชนกับ collider เมื่อมันชนกับ collider ข้อมูล (raycasthit) ของ object ที่ชนและตำแหน่งภายในฉากจะถูกส่งกลับ สำหรับรายละเอียดเพิ่มเติมเกี่ยวกับ unity raycast กรุณาทบทวนคู่มือ unity 📘 unity raycast https //docs unity3d com/manual/camerarays html https //docs unity3d com/manual/camerarays html unity raycast สามารถใช้ใน zepeto script โดยทำตามขั้นตอนต่อไปนี้ ก่อนอื่น ให้นำเข้าคลาสที่เกี่ยวข้องกับ raycast import { physics, raycasthit } from 'unityengine'; ต่อไปนี้คือตัวอย่างโค้ดสำหรับฟังก์ชัน raycast raycast import { zepetoscriptbehaviour } from 'zepeto script'; import { physics, raycasthit, input, camera } from 'unityengine'; export default class raycastsample extends zepetoscriptbehaviour { update() { this mousecontrol(); } mousecontrol() { if (input getmousebuttondown(0)) { let ray = camera main screenpointtoray(input mouseposition); // โปรดทราบว่าเพื่อรักษาข้อมูล raycasthit เป็นพารามิเตอร์ผลลัพธ์ มันต้องถูกห่อหุ้มในแท็ก $ref // เนื่องจากเราต้องการคุณสมบัติ out เป็นพารามิเตอร์ เราจึงสร้างการอ้างอิงโดยไม่ต้องสร้างวัตถุจริง let ref = $ref\<raycasthit>(); if (physics raycast(ray, ref, 1000)) { // เพื่อตรวจสอบข้อมูลการชนที่ส่งกลับ โปรดจำไว้ว่าต้องคลายการอ้างอิงโดยใช้ $unref let hitinfo = $unref(ref); console log(`ตรวจพบการชน!`); console log(`hitinfo collider name ${hitinfo collider name}`); } else { console log(`ไม่สามารถตรวจจับการชนได้`); } } } } 📘 โปรดดูคู่มือต่อไปนี้เพื่อคำอธิบายเกี่ยวกับ $ref และ $unref ที่ใช้ในสคริปต์ \[ $ref & $unref docid\ wnve go7fzilmxlni7lyr ] ผ่านโค้ดทดสอบ คุณสามารถตรวจสอบว่าข้อมูลของวัตถุถูกส่งออกโดยการคลิกที่ลูกบาศก์ด้วยตัวชี้เมาส์ในฉาก หาข้อมูลเพิ่มเติมเกี่ยวกับ raycast api ที่ใช้ใน zepeto script ได้โดยไปที่ลิงก์ด้านล่าง 📘 raycast https //docs unity3d com/scriptreference/physics raycast html https //docs unity3d com/scriptreference/physics raycast html