首页 > 解决方案 > 如何在 ursina 引擎中对角色施加重力?

问题描述

(Python Ursina 引擎)

如何在 ursina 引擎上添加重力?这是我正在使用的代码: https ://github.com/pokepetter/ursina/blob/master/samples/terraria_clone.py

from ursina import *
from math import floor


app = Ursina()

size = 32
plane = Entity(model='quad', color=color.azure, origin=(-.5,-.5), z=10, collider='box', scale=size) # create an invisible plane for the mouse to collide with
grid = [[Entity(model='quad', position=(x,y), texture='white_cube', enabled=False) for y in range(size)] for x in range(size)] # make 2d array of entities
player = Entity(model='quad', color=color.orange, position=(16,16,-.1))
cursor = Entity(model=Quad(mode='line'), color=color.lime)

def update():
    if mouse.hovered_entity == plane:
        # round the cursor position
        cursor.position = mouse.world_point
        cursor.x = round(cursor.x, 0)
        cursor.y = round(cursor.y, 0)

    # check the grid if the player can move there
    if held_keys['a'] and not grid[int(player.x)][int(player.y)].enabled:
        player.x -= 5 * time.dt
    if held_keys['d'] and not grid[int(player.x)+1][int(player.y)].enabled:
        player.x += 5 * time.dt



def input(key):
    if key == 'left mouse down':
        grid[int(cursor.x)][int(cursor.y)].enabled = True
    if key == 'right mouse down':
        grid[int(cursor.x)][int(cursor.y)].enabled = False


camera.orthographic = True
camera.fov = 10
camera.position = (16,18)

# enable all tiles lower than 16 to make a ground
for column in grid:
    for e in column:
        if e.y <= 15:
            e.enabled = True

app.run()

标签: pythonursina

解决方案


您可以使用内置的 2D 平台游戏控制器:

from ursina.prefabs.platformer_controller_2d import PlatformerController2d

player = PlatformerController2d(position=(16, 20, -.1), scale_y=1)

def update():
   # other keys...
   if held_keys['space']:
        player.y += 1

这为您提供了基本的跳跃控制,但更好的实现方式是将关卡定义为网格实体并将其设置为玩家的traverse_target,如平台游戏教程中所述。


推荐阅读