I’m trying to make one of those Cookie Clicker-esque games where the things you are supposed to be clicking randomly move away from you, and while I got the menus working, getting the actual stuff to work is not working. I managed to get Sprite click detection working but random movements or bouncing off the edge (or preventing it from going off-screen) won’t work. Heres my GDScript code:
extends StaticBody2D
var speed = randf_range(50, 150)
var value = randf_range(-1, 1)
var direction = Vector2(value,value).normalized()
var speed_variation_rate = 0.5
var direction_variation_rate = 0.5
var viewport_size = get_viewport_rect().size
func _ready():
# random movement control #
var val1 = randf_range(0, get_viewport().size.x)
var val2 = randf_range(0, get_viewport().size.y)
position = Vector2(val1, val2)
func _physics_process(delta):
rand_speed_dir()
position += direction * speed * delta
# check if its touching the edge #
if position.x > screensize.x:
position.x = screensize.x
if position.x < 0:
position.x = 0
if position.y > screensize.y:
position.y = screensize.y
if position.y < 0:
position.y = 0
# random movement control #
func rand_speed_dir():
if randf() < speed_variation_rate:
speed = randf_range(50, 150)
if randf() < direction_variation_rate:
direction = Vector2(value, value).normalized()
I tried rewriting/changing the “bounce off edge” code and the sprite would just stand still in the top right corner and wouldn’t move. If I tried without it, again it’ll just go off-screen which would make the game unfair since random direction control is also broken (as in it can’t rotate randomly from going left to up to down, you get the idea.)
Daniel Budgieton is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.