How to make a rotatearound ping pong direction and speed changing behavior?

The script behavior now is when the camera inside the method StartCameraRotation is reaching the maximum rotation speed to 180 then it’s at once changing the rotatearound direction keep rotating that direction for x seconds then change direction and again keep rotating around for that direction for x seconds and so on a ping pong.

but I want some different behavior, I want that when the camera rotate around is reaching the maximum rotation speed of 180 then it will wait for example 5 seconds or so using timeToChangeDirection keep rotating around at this speed the same direction and after 5 seconds start at the same time smooth rotate to the other direction and also to slow down decrease the speed to 0 using this variable timeToReachMaxSpeed so it will take to speed up and slow down the same time. then when the speed is reaching to 0 wait again some seconds using timeToChangeDirection then start changing direction to the other direction and also smooth slowly speed up again back to 180. and so on. this kind of ping pong.

so in general , the behavior should be ping pong between the directions and speed of rotation with staying at each point some x seconds. stay at speed 0 timeToChangeDirection and then when reaching to 180 stay for timeToChangeDirection before changing direction and speed.

using System.Collections;
using TMPro;
using UnityEngine;

public class BallManager : MonoBehaviour
{
    public GameObject ballPrefab;
    public int numberOfBalls = 10;
    public float fallSpeed = 5;
    public float spawningSpeed = 1;
    public float ballSize = 1f;
    public bool randomSize = false;
    public TextMeshProUGUI ballCountText; // Reference to the TextMeshPro Text
    public float maxRotationSpeed = 180.0f;
    public float rotationSpeed = 10.0f; // Initial rotation speed (when it starts)
    public float timeToReachMaxSpeed = 30.0f; // Time in seconds to reach maximum rotation speed
    public float timeToChangeDirection = 5.0f;
    public float currentRotationSpeed; // Variable to display the current rotation speed in the inspector

    private int ballCount; // Counter for the number of balls
    private Transform cameraTransform;

    private void Start()
    {
        cameraTransform = Camera.main.transform;
        currentRotationSpeed = rotationSpeed; // Initialize currentRotationSpeed
        StartCoroutine(SpawnBalls());
        StartCoroutine(StartCameraRotation());
    }

    private IEnumerator SpawnBalls()
    {
        for (int i = 0; i < numberOfBalls; i++)
        {
            GameObject ball = Instantiate(ballPrefab, transform.position, Quaternion.identity);

            if (randomSize)
            {
                float randomScale = Random.Range(0.5f, 2.0f); // Random size between 0.5 and 2
                ball.transform.localScale = new Vector3(randomScale, randomScale, randomScale);
            }
            else
            {
                ball.transform.localScale = new Vector3(ballSize, ballSize, ballSize);
            }

            Rigidbody rb = ball.GetComponent<Rigidbody>();
            rb.velocity = Vector3.down * fallSpeed;

            // Randomize bouncing direction
            Vector3 randomDirection = new Vector3(Random.Range(-1f, 1f), 0, Random.Range(-1f, 1f)).normalized;
            rb.AddForce(randomDirection * 5f, ForceMode.Impulse);

            // Increase the ball count and update the TextMeshPro Text
            ballCount++;
            ballCountText.text = "Balls: " + ballCount;

            yield return new WaitForSeconds(spawningSpeed); // Time delay between spawning balls
        }
    }

    private IEnumerator StartCameraRotation()
    {
        float timer = 0.0f;

        while (timer < timeToReachMaxSpeed)
        {
            timer += Time.deltaTime;
            currentRotationSpeed = Mathf.Lerp(0, maxRotationSpeed, timer / timeToReachMaxSpeed);

            // Rotate the camera around the target
            cameraTransform.RotateAround(transform.position, Vector3.up, currentRotationSpeed * Time.deltaTime);

            yield return null;
        }

        // Now, keep rotating at the maximum speed
        while (true)
        {
            cameraTransform.RotateAround(transform.position, Vector3.up, maxRotationSpeed * Time.deltaTime);

            // If it's time to change direction
            if (timer > timeToChangeDirection)
            {
                // Reset the timer and reverse the rotation direction
                timer = 0.0f;
                maxRotationSpeed *= -1;
            }

            timer += Time.deltaTime;
            yield return null;
        }
    }
}

Camera stuff is pretty tricky… you may wish to consider using Cinemachine from the Unity Package Manager.

There’s even a dedicated forum: Unity Engine - Unity Discussions

If you insist on making your own camera controller, the simplest way to do it is to think in terms of two Vector3 points in space: where the camera is LOCATED and where the camera is LOOKING.

private Vector3 WhereMyCameraIsLocated;
private Vector3 WhatMyCameraIsLookingAt;

void LateUpdate()
{
  cam.transform.position = WhereMyCameraIsLocated;
  cam.transform.LookAt( WhatMyCameraIsLookingAt);
}

Then you just need to update the above two points based on your GameObjects, no need to fiddle with rotations.

Otherwise, if you want to debug your own code above, use this approach:

Time to start debugging! Here is how you can begin your exciting new debugging adventures:

You must find a way to get the information you need in order to reason about what the problem is.

Once you understand what the problem is, you may begin to reason about a solution to the problem.

What is often happening in these cases is one of the following:

  • the code you think is executing is not actually executing at all
  • the code is executing far EARLIER or LATER than you think
  • the code is executing far LESS OFTEN than you think
  • the code is executing far MORE OFTEN than you think
  • the code is executing on another GameObject than you think it is
  • you’re getting an error or warning and you haven’t noticed it in the console window

To help gain more insight into your problem, I recommend liberally sprinkling Debug.Log() statements through your code to display information in realtime.

Doing this should help you answer these types of questions:

  • is this code even running? which parts are running? how often does it run? what order does it run in?
  • what are the names of the GameObjects or Components involved?
  • what are the values of the variables involved? Are they initialized? Are the values reasonable?
  • are you meeting ALL the requirements to receive callbacks such as triggers / colliders (review the documentation)

Knowing this information will help you reason about the behavior you are seeing.

You can also supply a second argument to Debug.Log() and when you click the message, it will highlight the object in scene, such as Debug.Log("Problem!",this);

If your problem would benefit from in-scene or in-game visualization, Debug.DrawRay() or Debug.DrawLine() can help you visualize things like rays (used in raycasting) or distances.

You can also call Debug.Break() to pause the Editor when certain interesting pieces of code run, and then study the scene manually, looking for all the parts, where they are, what scripts are on them, etc.

You can also call GameObject.CreatePrimitive() to emplace debug-marker-ish objects in the scene at runtime.

You could also just display various important quantities in UI Text elements to watch them change as you play the game.

Visit Google for how to see console output from builds. If you are running a mobile device you can also view the console output. Google for how on your particular mobile target, such as this answer for iOS: How To - Capturing Device Logs on iOS or this answer for Android: How To - Capturing Device Logs on Android

If you are working in VR, it might be useful to make your on onscreen log output, or integrate one from the asset store, so you can see what is happening as you operate your software.

Another useful approach is to temporarily strip out everything besides what is necessary to prove your issue. This can simplify and isolate compounding effects of other items in your scene or prefab.

If your problem is with OnCollision-type functions, print the name of what is passed in!

Here’s an example of putting in a laser-focused Debug.Log() and how that can save you a TON of time wallowing around speculating what might be going wrong:

“When in doubt, print it out!™” - Kurt Dekker (and many others)

Note: the print() function is an alias for Debug.Log() provided by the MonoBehaviour class.

Smoothing movement between any two particular values, such as for easing speeds / positions / rotations:

You have currentQuantity and desiredQuantity.

  • only set desiredQuantity
  • the code always moves currentQuantity towards desiredQuantity
  • read currentQuantity for the smoothed value

Works for floats, Vectors, Colors, Quaternions, anything continuous or lerp-able.

The code: SmoothMovement.cs · GitHub

Another approach would be to use a tweening package such as LeanTween, DOTween or iTween.

    void Update()
    {
        float a=Mathf.SmoothStep(90,-90,Mathf.PingPong((Time.time/5)%2,1.0f));
        transform.eulerAngles=new Vector3(0,a,0);
    }
1 Like