Movement of Objects in a simulation

后端 未结 4 1444
轮回少年
轮回少年 2021-01-26 03:45

i am currently making a flash \"pond\" with fishes in it, and i have the ability to add food pellets onto the pond, how should i make the movement of my fishes to the food x,y l

4条回答
  •  无人及你
    2021-01-26 04:41

    This should explain exactly how to move your objects around. Obviously you will need to change the Sprite to whatever class your using for your fish/food/etc. Your fish object will either need a property for speed. such as: public var speed:int = 5; Or you can just define one in your main simulation for all the fish. ( I would prefer having variable speed fish myself)

        // This can be done faster but this is to show you how it works.
        public function moveObject(obj:Sprite, target:Sprite):void
        {
            // We start by getting the distances along the x and y axis
            var dx:Number = target.x - obj.x;
            var dy:Number = target.y - obj.y;
    
            // Basic distance check with pythagorean theorem. We don't need
            // to get the Square Roots because if it is smaller squared it
            // will still be smaller once we get the square roots and thus
            // will just be a waste of time.
            if (dx * dx + dy * dy < obj.speed * obj.speed)
            {
                // Since we are within one time step of speed we will go past it
                // if we keep going so just lock the position in place.
                obj.x = target.x;
                obj.y = target.y;
            }
            else
            {
                // we aren't there yet so lets rock.
    
                // get the angle in radians given the distance along the x and y axis.
                var angleRads:Number = Math.atan2(dy, dx);
    
                // get our velocity along the x and y axis
                // NOTE: remember how the flash coordinate system is laid out.
                // we need to calc cos along the x and sin along the y.
                var vx:Number = Math.cos(angleRads) * obj.speed;
                var vy:Number = Math.sin(angleRads) * obj.speed;
    
                // now that we have our speeds we can add it to the objects 
                // current position and thus create a nice smooth movement per
                // frame.
                obj.x += vx;
                obj.y += vy;
    
                // This will lock the rotation of the object to the direction
                // the object is traveling in.
                // NOTE: don't forget when you make your objects that for flash
                // rotation of Zero = pointing to the right (+x)
                obj.rotation = angleRads * 180 / Math.PI;
            }
        }
    

    Hope this helps, any questions just ask.

    Edit: You don't need to add a reference to the stage in a Sprite or MovieClip they already have access to the stage.

提交回复
热议问题