Animated Pickup - Random Floating + Rotation Values

Here is a simple script I’ve added to my pickup Sword (can be added to any object) that moves the object up and down + 360degrees rotation based on a random value from a Min/Max. It was based on the “Mathf.Sin() For Oscillation” lesson from Complete C# Unity Game Developer 3D - Project Boost with a bit of simplification + random values from me :grinning:

Why I like this approach: the distance / rotation / time values are all randomly calculated in start. This gives each object a “unique” feel. Here’s how it looks in action

I would be interested to know if this sort of code would be problematic on multiple objects since it uses the Update to “animate” them. If you know of a better/easier way to achieve this, please share :slight_smile: .

I’ve created a new namespace for the script called “RPG.Pickups” - This is optional

namespace RPG.Pickups
{
    public class pickupFloatingRotationAnimation : MonoBehaviour
    {
        private float originalY;
        [SerializeField] private float distanceMin = 5f;
        [SerializeField] private float distanceMax = 20f;
        private float randomFloat;
        [SerializeField] private float timeMin = 5f;
        [SerializeField] private float timeMax = 20f;
        private float randomTime;
        [SerializeField] private float rotationMin = 5f;
        [SerializeField] private float rotationMax = 20f;
        private float randomRotation;



        void Start()
        {
            this.originalY = this.transform.position.y;
            randomFloat = Random.Range(distanceMin, distanceMax);
            randomTime = Random.Range(timeMin, timeMax);
            randomRotation = Random.Range(rotationMin, rotationMax);
        }
        void Update()
        {
            //We Rotate the Object here
            gameObject.transform.Rotate(new Vector3(0f, randomRotation, 0f) * Time.deltaTime);
            //We Move the Object here - The distance and time is random for each object
            gameObject.transform.position = new Vector3(transform.position.x,
                originalY + (Mathf.Sin(randomTime + Time.time) * randomFloat), transform.position.z);

        }
    }

}

2 Likes

Well done!

1 Like

Privacy & Terms