返回首页

Ursina 3D 中的距离和碰撞

Ursina 中 distance()、distance_2d()、distance_xz() 和 intersects() 函数指南。距离计算、碰撞检测、AI 和物品拾取的代码示例,用于 3D 游戏。

Ursina:用于游戏的 distance 和 intersects
Advertisement 728x90

Ursina中3D游戏的距离与碰撞检测

在Ursina中,distance()distance_2d()distance_xz() 函数可精确计算3D空间中物体之间的距离。intersects() 方法则通过碰撞体检测碰撞。这些工具对于实现探测、物品拾取和AI行为等机制至关重要。

距离计算函数

distance() 函数计算两个 Entity 对象中心在X、Y、Z三个轴上的欧几里得距离:

from ursina import *
from ursina.prefabs.first_person_controller import FirstPersonController
app = Ursina()
ground = Entity(model='plane', texture='grass', scale=20, collider='box')
player = FirstPersonController(position=(0, 2, 0))
sphere = Entity(position=(3, 4, 0), model='sphere', color=color.blue)
Sky()

def update():
    dist = distance(player, sphere)
    print(f"距离英雄到球体: {dist:.2f}")

app.run()

公式:√((x₂-x₁)² + (y₂-y₁)² + (z₂-z₁)²)。适用于完整的空间分析。

Google AdInline article slot

distance_2d() 忽略Z轴,在X-Y平面内运算:

from ursina import * 
from ursina.prefabs.first_person_controller import FirstPersonController 
app = Ursina() 
ground = Entity( 
    model='plane', 
    texture='grass', 
    scale=20, 
    collider='box' 
) 
player = FirstPersonController(position=(0, 2, 0)) 
sphere = Entity(position=(3, 4, 0), model='sphere', color=color.blue) 
Sky() 

def update(): 
    dist = distance_2d(player, sphere) 
    print(f"2D距离从英雄到球体: {dist:.2f}") 

app.run()

适用于UI元素或处于同一高度的物体。

distance_xz() 专注于水平的X-Z平面,忽略Y轴:

Google AdInline article slot
from ursina import * 
from ursina.prefabs.first_person_controller import FirstPersonController 
app = Ursina() 
ground = Entity( 
    model='plane', 
    texture='grass', 
    scale=20, 
    collider='box' 
) 
player = FirstPersonController(position=(0, 2, 0)) 
sphere = Entity(position=(3, 4, 0), model='sphere', color=color.blue) 
Sky() 

def update(): 
    dist = distance_xz(player, sphere) 
    print(f"水平距离从英雄到球体: {dist:.2f}") 

app.run()

特别适合地面型AI,垂直位置不重要时使用。

intersects() 碰撞系统

intersects() 方法通过Panda3D的 CollisionTraverser 检测碰撞体(盒形、球形、网格)之间的碰撞。两个对象都必须设置 collider 并将 collision=True

返回一个 HitInfo 对象,包含以下字段:

Google AdInline article slot
  • hit:布尔值,表示是否发生碰撞
  • entity:碰撞的对象
  • point:撞击坐标
  • distance:到撞击点的距离

示例1:墙体检测

from ursina import *
app = Ursina()
player = Entity(model='cube', color=color.orange, collider='box')
wall = Entity(model='cube', position=(5,0,0), scale=(1,5,5), collider='box', color=color.red)

def update():
    player.x += 0.1 * time.dt
    hit_info = player.intersects()
    if hit_info.hit:
        print("碰撞!")
        print(f"与: {hit_info.entity}")
        print(f"撞击点: {hit_info.point}")
        print(f"到撞击点距离: {hit_info.distance:.2f}")

app.run()

示例2:物品拾取

from ursina import *
from ursina.prefabs.first_person_controller import FirstPersonController
app = Ursina()
ground = Entity(model='plane', texture='grass', scale=10, collider='box')
player = FirstPersonController(model='cube', origin_y=-.5)
pickup = Entity(model='sphere', position=(1,.5,3), collider='box')

def update():
    hit_info = player.intersects()
    if hit_info.hit and hit_info.entity == pickup:
        print('物品已拾取!')
        destroy(pickup)

app.run()

相比 distance(),对复杂形状更准确。

示例3:子弹系统

import random
from ursina import *
app = Ursina()

class Bullet(Entity):
    def __init__(self, position, direction):
        super().__init__(
            model='sphere',
            scale=.1,
            speed=15,
            collider='sphere',
            position=position,
            color=color.yellow,
            name='bullet'
        )
        self.direction = direction.normalized()

    def update(self):
        self.position += self.direction * time.dt * self.speed
        hit_info = self.intersects(ignore=(self,))
        if hit_info.hit:
            print(f"子弹击中 {hit_info.entity.name}!")
            destroy(self)

class Enemy(Entity):
    def __init__(self):
        super().__init__(
            model='cube',
            color=color.red,
            scale=1,
            collider='box',
            name='enemy'
        )
        self.x = random.choice([-4, 4])
        self.z = random.choice([-4, 4])

for i in range(5):
    Enemy()
player = Entity(model='cube', color=color.blue, position=(0, 0, 0))
shoot_timer = 0

def update():
    global shoot_timer
    shoot_timer += time.dt
    if shoot_timer >= 1:
        shoot_timer = 0
        random_direction = Vec3(
            random.uniform(-1, 1),
            random.uniform(-1, 1),
            random.uniform(-1, 1)
        ).normalized()
        bullet = Bullet(
            position=player.position,
            direction=random_direction
        )

app.run()

建议使用 raycast() 实现精准命中,而非物理弹丸。

实际应用场景

按距离拾取物品:

from ursina import *
from ursina.prefabs.first_person_controller import FirstPersonController
app = Ursina()
ground = Entity(model='plane', texture='grass', scale=10, collider='box')
player = FirstPersonController(model='cube', origin_y=-.5, color=color.orange, has_pickup=False)
pickup = Entity(model='sphere', position=(1,.5,3))

def update():
    if not player.has_pickup and distance(player, pickup) < pickup.scale_x / 2:
        print('物品已拾取!')
        player.has_pickup = True
        pickup.animate_scale(0, duration=.1)
        destroy(pickup, delay=.1)

app.run()

带探测区域的敌人AI:

from ursina import *
app = Ursina()
player = Entity(model='cube', position=(0, 0, 0), color=color.blue)
ground = Entity(model='plane', scale=20, color=color.dark_gray, y=-1)

class Enemy(Entity):
    def __init__(self, **kwargs):
        super().__init__(model='cube', scale_y=2, origin_y=-.5, color=color.light_gray, **kwargs)
        self.original_color = self.color
        self.detection_radius = 10

    def update(self):
        dist = distance_xz(player.position, self.position)
        if dist > self.detection_radius:
            self.color = self.original_color
            return
        self.color = color.red
        self.look_at_2d(player.position, 'y')
        if dist > 2:
            self.position += self.forward * time.dt * 3

enemies = [Enemy(x=x * 5, z=5) for x in range(-2, 3)]

def update():
    player.x += held_keys['d'] * time.dt * 5

app.run()

核心要点

  • 使用 distance() 进行全3D距离计算,distance_2d() 用于X-Y平面,distance_xz() 用于水平X-Z平面。
  • intersects() 需要双方均设置碰撞体,并返回详细的 HitInfo 信息。
  • 子弹系统推荐使用 raycast() 而非物理实体。
  • 结合 distance()intersects() 可构建交互区域与精准碰撞检测。
  • intersects() 中始终使用 ignore=(self,) 防止自碰撞。

— Editorial Team

Advertisement 728x90

继续阅读