Making a main screen in Ursina - python

I am currently making a game with Ursina and i've been struggling to find a code to make a Main-Starting-Screen to start the game or show controlls.
Here is my game code:
game = Ursina()
ground = Entity(model = "untitled.blend", texture = "Soul Sand.jpg", scale = 400, collider = "mesh")
player = FirstPersonController(model = "player.blend", position = (-6.39844, 148.284, 62.5471),jump_height = 7, jump_duration = 0.5, speed = 10, texture = "Player Texture.jpg", collider = "mesh")
camera.z = None
health_bar = HealthBar(bar_color=color.lime.tint(-.25), roundness=.5, value=100)
def input(key):
if key == "shift":
player.speed = 25
elif key == "control":
player.speed = 10
house = Entity(model = "House.blend", texture = "Tree Texture.jpg", scale = 2, collider = "mesh", position = (0, 146.3, 15))
tree = Entity(model = "Tree.blend", scale = 15, texture = "Tree Texture.jpg", collider = "mesh", position = (15.5488, 140, 55.0674))
game.run()

You could try just displaying a quad model which is a 2d square
Menuback=Entity(model="quad"scale=(10,10))
and just make
Allother entities to .enabled=False
And the menu to true
Create a button
And onclick menuback.enabled =False
And the rest od entities set on true
Here is the ursina docs if u need to look at some stuff
https://www.ursinaengine.org/api_reference.html

Related

Ursina - Make button only clickable when within a certain radius from camera

I have created a 3d button in ursina, but suppose we are a kilometer away from the button, we can still press it. Where is the logic in it? I would like to make the button clickable only when in a certain radius from it.
horror_gamemode = Button(parent = scene, model = 'cube', texture = None, color = color.black, highlight_color = color.dark_gray, scale = 1, position = (3, -49, 4), collider = 'mesh')
If I got it right, you want to make a button not clickable when we are over, lets say, 100 meters. For that you can use ursina's distance function to calculate the position between the camera and the button and if it is less that 100 meters, then make it clickable, otherwise unclickable (you can use .disabled = False # or True).
Example:
from ursina import *
from ursina.prefabs import *
app = Ursina()
horror_gamemode = Button(parent = scene, model = 'cube', texture = None, color = color.black, highlight_color = color.dark_gray, scale = 1, position = (0, 0, 0), collider = 'mesh')
def some_random_func():
print("HI")
def update():
if (distance(camera, horror_gamemode) < 50):
button.color = color.green
button.disabled = False
horror_gamemode.on_click = some_random_func
else:
button.color = color.red
print(distance(horror_gamemode, camera))
button.disabled = True
horror_gamemode.on_click = None
EditorCamera()
app.run()

Collisions in Visual Python

I'm currently doing a school project that wants 2D pong made in Visual Python. Right now, I've set my current collisions of the 2 paddles at the bottom of the code. When it runs, it decides to go through it and hit the green walls (Which I will change to clear walls later). Even with the paddle no where near the ball, it still detects a "wall" present and bounces off, which I'm pretty sure its creating a massive skinny wall on the x axis where the paddle is, but is stretched vertically. I do not know any other way my teacher taught other than this way. Any help would be greatly appreciated!
from visual import *
# Title Screen
def TitleScreen():
# Display
sceneTest = display(title='Pong', x=0, y=0, width=950,
height=950, center=(5,0,0), background=(1,1,1))
#autoscale
sceneTest.autoscale = False
#Back Wall
wallBack = box(pos = vector(2,0,-2), size=(50,50,0.2), color = color.black)
#Ball
ballPong = box(pos = vector(5,1,0), size=(0.5,0.5,0.01), color = color.white)
#Left Stick
stick1 = box(pos = vector(-6,0,0), size=(0.5, 5, 0.2), color = color.white)
#Right Stick
stick2 = box(pos = vector(16,0,0), size=(0.5, 5, 0.2), color = color.white)
# Title Text
titleScreenText = text(text = "Pong", pos = (5,9, 0), align = "center",
depth = 0.01, height = 1.5, width = 1.5,
color = color.white)
# Start Game
titleScreenText = text(text = "Press E to Start", pos = (-1.5,-8.5, 0),
depth = 0.01, height = 1.5, width = 1.5,
color = color.white)
# Main Loop for starting game
while True:
rate(30)
if sceneTest.kb.keys:
key = sceneTest.kb.getkey()
if key == "e":
sceneTest.delete()
pongGame()
# Main Game Loop
def pongGame():
# Game Display
newDisplay = display(title='Pong', x=0, y=0,width=950,
height=950, center=(5,0,0), background=(1,1,1))
newDisplay.autoscale = False
# BlackWall
wallBack = box(pos = vector(2.5,0,-2), size=(50,50,0.2), color = color.black)
ball2 = box(pos = vector(5,0,0), size=(0.5,0.5,0.5), color = color.white)
# Stick Paddle 1
stick1New = box(pos = vector(-6,0,0), size=(0.5, 5, 0.2), color = color.white)
# Stick Paddle 2
stick2New = box(pos = vector(16,0,0), size=(0.5, 5, 0.2), color = color.white)
#Clear Wall Left Boundary color = color.green) opacity= 0.01
wallClear1 = box(pos=vector(-6.5,0,0), size=(0.2,22,0.3), color = color.green)
#Clear Wall Right Boundary
wallClear2 = box(pos=vector(16.5,0,0), size=(0.2,22,0.3), color = color.green)
# Clear Wall Top Boundary
wallClear3 = box(pos=vector(5,11,0), size=(23,0.2,0.3), color = color.green)
# Clear Bottom Boudary
wallClear4 = box(pos=vector(5,-11,0), size=(23,0.2,0.3), color = color.green)
# Ball Velocity Initial
ball2.velocity = vector(11,0)
deltaT = 0.005
t = 0.0
# Scoreboard
player1Score = 0
player2Score = 0
scoreText = ("{} : {}".format(player1Score, player2Score))
scoreTextDisplay = text(text = scoreText, pos = (5,9, 0), align = "center", depth = 0.1, height = 1.5, width = 1.5, color = color.white)
while True:
# Refresh
rate(100)
# Ball Velocity while Running
t = t + deltaT
ball2.pos = ball2.pos + ball2.velocity*deltaT
##
## # Literal Aimbot
## stick2New.velocity = vector(0,3)
## stick2New.pos = stick2New.pos + stick2New.velocity*deltaT
## stick2New.pos.y = ball2.pos.y
##
# Player 1 Input/Controls
if newDisplay.kb.keys:
keyNew = newDisplay.kb.getkey()
# Moving Up
if keyNew == "w":
stick1New.pos.y = stick1New.pos.y + 0.25
# Moving Down
if keyNew == "s":
stick1New.pos.y = stick1New.pos.y - 0.25
# If ball hits Right wall
if ball2.pos.x > wallClear2.pos.x:
ball2.velocity.x = ball2.velocity.x
player1Score = player1Score + 1
ball2.pos = (5,0,0)
# If ball hits Left wall
if ball2.pos.x < wallClear1.pos.x:
ball2.velocity.x = ball2.velocity.x
player2Score = player2Score + 1
ball2.pos = (5,0,0)
# If the Ball hits the top of the Wall
if ball2.pos.y > wallClear3.pos.y:
ball2.velocity.y = -ball2.velocity.y
# If the Ball hits the bottom of the Wall
if ball2.pos.y < wallClear4.pos.y:
ball2.velocity.y = -ball2.velocity.y
# Collisions Check OLD
# if ball hits right paddle
## if ball2.pos.x < stick2New.pos.x: #or ball2.pos.x > stick2New.pos.x:
## ball2.velocity.x = -ball2.velocity.x
## if ball2.pos.x > (stick2New.pos.x == -6) or ball2.pos.x < (stick2New.pos.x > -6):
## ball2.velocity.x = -ball2.velocity.x
# if ball hits left paddle
if ball2.pos.x < stick1New.pos.x:
ball2.velocity.x = -ball2.velocity.x
if ball2.pos.x > stick2New.pos.x:
ball2.velocity.x = -ball2.velocity.x
TitleScreen()
You do not have any code to check the y coordinate of the ball when checking collisions with the paddles. This will make the paddles appear infinitely tall. You can incorporate some code like if (ball2.pos.x < stick1New.pos.x) and abs(ball2.pos.y-stick1New.pos.y) < 2.5: ball2.velocity.x*=-1; ball2.velocity.y *=-1;

enemy collision in ursina

i'm making a game in ursina and want to know how i can output something that says its true or false(like in a boolean). because the game that i am making needs collision with entity's. i have looked for a solution but i can't find anything. so people that use ursina please help me here is the code:
from ursina import *
import random
#variables
speed = 0.05
number_of_pokemon = 10
app = Ursina()
#textures
player_texture = load_texture('pokemon orange assets/player.png')
pokemon_texture1 = load_texture('pokemon orange assets/pokemon.png')
pokemon_texture2 = load_texture('pokemon orange assets/pokemon2.png')
pokemon_texture3 = load_texture('pokemon orange assets/pokemon3.png')
grass_texture = load_texture('pokemon orange assets/grass.png')
textbox_texture = load_texture('pokemon orange assets/textbox.png')
missingno_texture = load_texture('pokemon orange assets/missingno.png')
pokemontextures = [pokemon_texture1, pokemon_texture2, pokemon_texture3]
#entitys: pokemon(s), player, textbox, battles
player = Entity(model = 'cube', texture = player_texture, scale = (1,1,0), position =
(0,0,-0.1))
#textbox = Entity(model ='cube', texture = textbox_texture, scale = (5,1,0), position =
(0,-3,0))
#spawns pokemon
number = random.uniform(0,100)
if(number == 100):
for i in range (100):
pokemon = Entity(model ='cube', texture = missingno_texture, scale = (1,2,0),
position = (random.uniform(-10,10),random.uniform(-10,10),random.uniform(-10,10)))
else:
for i in range(number_of_pokemon):
pokemon = Entity(model ='cube', texture = random.choice(pokemontextures), scale = (1.5,1.5,0), position = (random.uniform(-5,5),random.uniform(-4,4),-0.1))
#spawns grass
for y in range(20):
for x in range(20):
grass = Entity(model ='cube', texture = grass_texture, scale = (1,1,0), position = (x - 10,y - 10,0))
#movement
def update():
player.x += held_keys['d'] * speed
player.x -= held_keys['a'] * speed
player.y += held_keys['w'] * speed
player.y -= held_keys['s'] * speed
app.run()
Set a Collider and check if your entity intersects with another one:
player = Entity(model='cube',
texture=player_texture,
scale=(1, 1, 0),
position=(0, 0, -0.1),
collider='box') # <-- do the same for all pokemon entities
hit_info = player.intersects()
if hit_info.hit:
print(hit_info.entity)

Can't get attack animation to work for arcade library with python

I'm using a tutorial from arcade.academy and the game runs fine so far (a guy walking around collecting coins and scoring points) but I want to have an attack animation occur when the user presses Q so I can turn some of the coins into enemies and make a little RPG and increase my knowledge.
This is what I've got so far but for some reason the self.is_attacking boolean either doesn't trigger or isn't linked up properly.
Here's what I've got so far.
import arcade
import random
import os
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
SCREEN_TITLE = "Move with a Sprite Animation Example"
COIN_SCALE = 0.5
COIN_COUNT = 50
CHARACTER_SCALING = 1
MOVEMENT_SPEED = 5
UPDATES_PER_FRAME = 7
# Constants used to track if the player is facing left or right
RIGHT_FACING = 0
LEFT_FACING = 1
def load_texture_pair(filename):
"""
Load a texture pair, with the second being a mirror image.
"""
return [
arcade.load_texture(filename, scale=CHARACTER_SCALING),
arcade.load_texture(filename, scale=CHARACTER_SCALING, mirrored=True)
]
class PlayerCharacter(arcade.Sprite):
def __init__(self):
# Set up parent class
super().__init__()
# Default to face-right
self.character_face_direction = RIGHT_FACING
# Used for flipping between image sequences
self.cur_texture = 0
self.attack_texture = 0
# Track our state
self.jumping = False
self.climbing = False
self.is_on_ladder = False
self.is_attacking = False
# Adjust the collision box. Default includes too much empty space
# side-to-side. Box is centered at sprite center, (0, 0)
self.points = [[-22, -64], [22, -64], [22, 28], [-22, 28]]
# --- Load Textures ---
# Images from Kenney.nl's Asset Pack 3
main_path = "images/Sprites/rogue like character/rogue like"
# main_path = "platform_tutorial/images/Female person/PNG/Poses/character_femalePerson"
# main_path = "platform_tutorial/images/Male person/PNG/Poses/character_malePerson"
# main_path = "platform_tutorial/images/Male adventurer/PNG/Poses/character_maleAdventurer"
# main_path = "platform_tutorial/images/Zombie/PNG/Poses/character_zombie"
# main_path = "platform_tutorial/images/Robot/PNG/Poses/character_robot"
# Load textures for idle standing
self.idle_texture_pair = load_texture_pair(f"{main_path} idle_Animation 1_0.png")
# Load textures for walking
self.walk_textures = []
for i in range(6):
texture = load_texture_pair(f"{main_path} run_Animation 1_{i}.png")
self.walk_textures.append(texture)
# Load textures for attacking
self.attack_textures = []
for i in range(10):
texture = load_texture_pair(f"{main_path} attack_Animation 1_{i}.png")
self.attack_textures.append(texture)
def update_animation(self, delta_time: float = 1/60):
# Figure out if we need to flip face left or right
if self.change_x < 0 and self.character_face_direction == RIGHT_FACING:
self.character_face_direction = LEFT_FACING
elif self.change_x > 0 and self.character_face_direction == LEFT_FACING:
self.character_face_direction = RIGHT_FACING
# Idle animation
if self.change_x == 0 and self.change_y == 0:
self.texture = self.idle_texture_pair[self.character_face_direction]
return
# Walking animation
self.cur_texture += 1
if self.cur_texture > 5 * UPDATES_PER_FRAME:
self.cur_texture = 0
self.texture = self.walk_textures[self.cur_texture // UPDATES_PER_FRAME][self.character_face_direction]
# Attacking animation
if self.is_attacking:
self.cur_texture += 1
if self.cur_texture > 9 * UPDATES_PER_FRAME:
self.cur_texture = 0
self.is_attacking = False
self.texture = self.attack_textures[self.cur_texture // UPDATES_PER_FRAME][self.character_face_direction]
class MyGame(arcade.Window):
# Main application class.
def __init__(self, width, height, title):
# Initializer
super().__init__(width, height, title)
# Set the working directory (where we expect to find files) to the same
# directory this .py file is in. You can leave this out of your own
# code, but it is needed to easily run the examples using "python -m"
# as mentioned at the top of this program.
file_path = os.path.dirname(os.path.abspath(__file__))
os.chdir(file_path)
# Set up the game and initialize the variables.
# Sprite lists
self.player_list = None
self.coin_list = None
# Set up the player
self.score = 0
self.player = None
self.is_attacking = False
def setup(self):
self.player_list = arcade.SpriteList()
self.coin_list = arcade.SpriteList()
# Set up the player
self.score = 0
self.player = PlayerCharacter()
self.player.center_x = SCREEN_WIDTH // 2
self.player.center_y = SCREEN_HEIGHT // 2
self.player.scale = 0.8
self.player_list.append(self.player)
for i in range(COIN_COUNT):
coin = arcade.AnimatedTimeSprite(scale=0.5)
coin.center_x = random.randrange(SCREEN_WIDTH)
coin.center_y = random.randrange(SCREEN_HEIGHT)
coin.textures = []
coin.textures.append(arcade.load_texture("images/items/Coingold.png", scale=COIN_SCALE))
coin.textures.append(arcade.load_texture("images/items/Coingold.png", scale=COIN_SCALE))
coin.textures.append(arcade.load_texture("images/items/Coingold.png", scale=COIN_SCALE))
coin.textures.append(arcade.load_texture("images/items/Coingold.png", scale=COIN_SCALE))
coin.textures.append(arcade.load_texture("images/items/Coingold.png", scale=COIN_SCALE))
coin.textures.append(arcade.load_texture("images/items/Coingold.png", scale=COIN_SCALE))
coin.cur_texture_index = random.randrange(len(coin.textures))
self.coin_list.append(coin)
# Set the background color
arcade.set_background_color(arcade.color.AMAZON)
def on_draw(self):
# Render the screen.
# This command has to happen before we start drawing
arcade.start_render()
# Draw all the sprites.
self.coin_list.draw()
self.player_list.draw()
# Put the text on the screen.
output = f"Score: {self.score}"
arcade.draw_text(output, 10, 20, arcade.color.WHITE, 14)
def on_key_press(self, key, modifiers):
# Called whenever a key is pressed.
if key == arcade.key.UP:
self.player.change_y = MOVEMENT_SPEED
elif key == arcade.key.DOWN:
self.player.change_y = -MOVEMENT_SPEED
elif key == arcade.key.LEFT:
self.player.change_x = -MOVEMENT_SPEED
elif key == arcade.key.RIGHT:
self.player.change_x = MOVEMENT_SPEED
elif key == arcade.key.Q:
self.is_attacking = True
def on_key_release(self, key, modifiers):
# Called when the user releases a key.
if key == arcade.key.UP or key == arcade.key.DOWN:
self.player.change_y = 0
elif key == arcade.key.LEFT or key == arcade.key.RIGHT:
self.player.change_x = 0
elif key == arcade.key.Q:
self.is_attacking = False
def on_update(self, delta_time):
# Movement and game logic
self.coin_list.update()
self.coin_list.update_animation()
self.player_list.update()
self.player_list.update_animation()
# Generate a list of all sprites that collided with the player.
hit_list = arcade.check_for_collision_with_list(self.player, self.coin_list)
# Loop through each colliding sprite, remove it, and add to the score.
for coin in hit_list:
coin.remove_from_sprite_lists()
self.score += 1
def main():
# Main method
window = MyGame(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE)
window.setup()
arcade.run()
if __name__ == "__main__":
main()
You can try setting
self.player.is_attacking=True

Scrolling text in pygame

How would I go about achieving scrolling text in pygame? As the Text class is derived from Sprite, I thought I would be able to wrap it in the usual way I would a Sprite object. Instead, it simply disappears off the left edge of the screen, never to return (I can't get it to bounce off each side either).
My aim with this program is to reinforce things I've just covered in some educational material. However, scrolling text wasn't one of them (would look cool though).
Thanks,
Dave
Code(specific block is under comment 'add scrolling text at bottom of screen'):
# Simon Says
# Displays sequences of sounds and/or colors which the user must repeat
from livewires import games, color
import random
# initialise screen
games.init(screen_width = 640, screen_height = 480, fps = 50)
class Game(object):
"""A sequence repeat game"""
def __init__(self):
"""Initialize Game object"""
# create key
self.menu_title = games.Text(value = "Key",
size = 25,
color = color.red,
top = 5,
left = games.screen.width - 100,
is_collideable = False)
self.menu_choice0 = games.Text(value = "0 - Quit",
size = 20,
color = color.red,
top = self.menu_title.bottom + 5,
left = games.screen.width - 120,
is_collideable = False)
self.menu_choice1 = games.Text(value = "1 - Yellow",
size = 20,
color = color.red,
top = self.menu_choice0.bottom + 5,
left = games.screen.width - 120,
is_collideable = False)
self.menu_choice2 = games.Text(value = "2 -Thrust sound",
size = 20,
color = color.red,
top = self.menu_choice1.bottom + 5,
left = games.screen.width - 120,
is_collideable = False)
games.screen.add(self.menu_title)
games.screen.add(self.menu_choice0)
games.screen.add(self.menu_choice1)
games.screen.add(self.menu_choice2)
# add scrolling text at bottom of screen
self.instructions = games.Text(value = "Repeat the sequence by entering the "
"corresponding number.",
size = 20,
color = color.green,
x = games.screen.width/2,
bottom = games.screen.height - 2,
dx = - 0.75)
games.screen.add(self.instructions)
# wrap
if self.instructions.left < 0:
self.instructions.left = games.screen.width
def play(self):
"""Play game"""
# load and set background
black_background = games.load_image("blackbackground.jpg", transparent = False)
games.screen.background = black_background
games.screen.mainloop()
def main():
sequence = Game()
sequence.play()
main()
I don't see anything that would handle it all for you in livewires. You could probably use livewires.Object with some custom code. Build your surface like livewires.game.Text does then, move it around. Or even make it tickable and keep track of what part of the text should be shown and blit just that part to the object surface.

Categories

Resources