如何在Python Ursina引擎中为角色添加重力效果
Ursina引擎2D项目添加重力效果实现方法
你可以基于现有代码做以下几处修改即可实现重力效果,还可额外添加跳跃支持:
- 新增重力、玩家垂直速度、跳跃力度三个全局参数,可根据手感自由调整数值
- 在update函数中每帧更新垂直速度,处理地面碰撞检测,避免玩家穿过方块
- 调整原有左右移动的碰撞判断逻辑,适配非整数y坐标的情况
- 可选在input函数中添加跳跃触发逻辑
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) # 新增重力相关参数 gravity = -22 # 重力加速度,数值越大下落越快 player_y_velocity = 0 # 玩家垂直方向速度 jump_force = 8 # 跳跃力度,数值越大跳的越高 on_ground = False # 标记玩家是否站在地面上 def update(): global player_y_velocity, on_ground 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) # 重力逻辑处理 player_y_velocity += gravity * time.dt target_y = player.y + player_y_velocity * time.dt # 检测脚下是否有方块 player_grid_x = int(player.x) player_bottom_y = target_y - 0.5 # 玩家底部的y坐标,因为quad默认中心为原点,高度为1 on_ground = False if player_bottom_y < size and player_grid_x >=0 and player_grid_x < size: if grid[player_grid_x][int(floor(player_bottom_y + 0.001))].enabled: # 碰到地面,重置速度,对齐到地面位置 player_y_velocity = 0 target_y = int(floor(player_bottom_y)) + 0.5 on_ground = True player.y = target_y # 调整后的左右移动逻辑 if held_keys['a'] and player_grid_x > 0: # 判断左侧同高度格子是否阻挡 if not grid[player_grid_x - 1][int(floor(player.y))].enabled: player.x -= 5 * time.dt if held_keys['d'] and player_grid_x < size -1: # 判断右侧同高度格子是否阻挡 if not grid[player_grid_x + 1][int(floor(player.y))].enabled: player.x += 5 * time.dt def input(key): global player_y_velocity, on_ground 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 # 新增跳跃逻辑,按空格跳跃 if key == 'space' and on_ground: player_y_velocity = jump_force 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()
如果不需要跳跃功能,直接删掉input函数里的空格判断相关代码即可。
内容的提问来源于stack exchange,提问作者John lennon
相关产品推荐
相关产品推荐

