Help with BGE script

I’m trying to make a cube bounce around to difference locations based on the value of a random integer. I think there is problem in the for loop.


import random
import bge
from random import uniform


cont = bge.logic.getCurrentController()
own = cont.owner


x = random.randint(1, 5)


own['actnr'] = x


for x in range(0, 3):


own.worldPosition.z = uniform(-6, 6)
own.worldPosition.y = uniform(-6, 6)
own.worldPosition.x = uniform(-6, 6)

The script works for me, didn’t you forget to put the spaces before the lines of the loop?

You go through the loop 3 times and set your object’s position each time all during a single frame. Because of this, you’ll only see the last position. If you want to actually see your object move to 3 different positions, you should remove the for loop just execute the script once per frame on 3 different frames.

In addition to what Mobious said:

Instead of setting each component individually, you can just use a list comprehension:


own.worldPosition = [uniform(-6, 6) for i in range(3)]

What do you mean? What I want to happen, is that the cube only teleports around if the random number is between 0 and 3.

Your current script generates a random number between 1 and 5, saves it as in the object property ‘actnr’, then goes through a for loop 3 times setting the object’s position randomly. The fact that you use x for both your random number and the for loop means nothing other than overwriting x’s original random value.

If you want the behavior you’ve described, you should use a conditional if statement to check if x is the the desired range instead of using a for loop.

Okay, I’ll try that out.

replace:


for x in range(0, 3):

with:


if 0<=x and x<=3: