0

I want to start making a 2D RPG game but I am stuck trying to get the player to not be able to walk through objects and I can't figure it out. I would like it so when I walk into/hit the rock, the player will stop moving in that direstion so the rock is a barrier. Can someone help me as soon as you can please.

from ursina import *
class Player(Entity):
    def __init__(self, x, y, speed):
        super().__init__()

        self.model="quad"
        self.scale=1
        self.x=x
        self.y=y
        self.speed=speed
        self.texture="player_idle.png"
        self.collider='box'

    def update(self):
        self.x+=(held_keys['d'] - held_keys['a'])*time.dt*speed
        self.y+=(held_keys['w'] - held_keys['s'])*time.dt*speed
        
    def input(self, key):
        if key=='w':
            self.texture='player_walk_1.png'
        if key=='s':
            self.texture='player_idle.png'
        if key=='d':
            self.texture='player_walk_right.png'
        if key=='a':
            self.texture='player_walk_left.png'
            
app=Ursina()

rock=Entity(model="quad", scale=1, position=(0,4,1),
            texture="rock.png", collider='box')

x=-2
y=-1
size=1
speed=3
player=Player(x, y, speed)

for m in range (8):
    duplicate(rock, x=size*(m+1))
    duplicate(rock, x=-size*(m+1))

app.run()

1 Answers1

1

You've added colliders, but you still need to check for collision. Example where we only move if a wall is not hit:

from ursina import *
app = Ursina()

class Player(Entity):

    def update(self):
        self.direction = Vec3(
            self.forward * (held_keys['w'] - held_keys['s'])
            + self.right * (held_keys['d'] - held_keys['a'])
            ).normalized()  # get the direction we're trying to walk in.

        origin = self.world_position + (self.up*.5) # the ray should start slightly up from the ground so we can walk up slopes or walk over small objects.
        hit_info = raycast(origin , self.direction, ignore=(self,), distance=.5, debug=False)
        if not hit_info.hit:
            self.position += self.direction * 5 * time.dt

Player(model='cube', origin_y=-.5, color=color.orange)
wall_left = Entity(model='cube', collider='box', scale_y=3, origin_y=-.5, color=color.azure, x=-4)
wall_right = duplicate(wall_left, x=4)
camera.y = 2

app.run()

More info here: https://www.ursinaengine.org/collision.html

pokepetter
  • 1,383
  • 5
  • 8