mercredi 5 août 2015

Random point outside of a set bounds?

I want to generate a point (x,y) that is outside of my screen. The reason for this is I want to tween an object towards the outside of the screen, and the reason for tweening rather than just giving it a random X and Y velocity is because for this instance tweening using greensock is simpler than creating an update loop.

So, what is an elegant way to generate that number? My current solution is crude and doesn't allow for things to tween towards corners.

var quad:int = irand(1, 4); //generates a random integer between and including the min and max
var maxX:Number = frame.width;
var minX:Number = -frame.width;
var maxY:Number = frame.height;
var minY:Number = -frame.height;

if (quad == 1) //top
{
    maxY = -frame.height;
    minY = -frame.height - 50;
}
else if (quad == 2) //left
{
    maxX = -frame.width;
    minX = -frame.width - 50;
}
else if (quad == 3) //bottom
{
    maxY = frame.height + 50;
    minY = frame.height;
}
else if (quad == 4) //right
{
    maxX =frame.width + 50;
    minX = frame.width;
}

//first param is duration in seconds
//rand generates a number between the given values      
objectToTween.tweenTo(rand(1,2), { 
                        x: rand(minX, maxX),
                        y: rand(minY, maxY),
                        repeat: -1,
                        yoyo: false,
                        scaleX: 1,
                        scaleY: 1,
                        delay: rand(0,1),
                        ease: Quad.easeIn});

So hopefully it's clear that this solution picks a random direction and tweens the object towards that direction. I'm wondering if there is a way to generate a random number between two given ranges. (such as, between -100 and 100, but excluding -50 through 50) and then applying that for 2 dimensions




Aucun commentaire:

Enregistrer un commentaire