Can we use other approach to move an obstacle

Hi, guys, I did movement obstacle without using Sin function, just did it before the lecture started. So, my question, could we use this technique also, pros are less calculations and faster code execution, cons - is not depending of frame time completion. On the screen it works without significant issues and quite smooth, cheers.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;


[DisallowMultipleComponent]
public class Oscillator : MonoBehaviour
{
    [SerializeField] Vector3 movementVector;

    [Range(0, 1)] [SerializeField] float movementFactor;
    [SerializeField] float movingStepPerUpdate = 0.02f;

    Vector3 startingPosition;
    float direction;

    // Start is called before the first frame update
    void Start()
    {
        startingPosition = gameObject.transform.position;

        direction = movementFactor < 1 ? 1f: -1f;
        
    }

    // Update is called once per frame
    void Update()
    {

        movementFactor += movingStepPerUpdate * direction;

        if (movementFactor > 1)
        {
            movementFactor = 1f;
            direction = -1f;

        } else if (movementFactor < 0)
        {
            movementFactor = 0.0f;
            direction = 1f;

        }


        gameObject.transform.position = startingPosition + movementVector * movementFactor;
    }
}

Hi Sergei,

Good job on developing your own solution. Maybe you could multiply movingStepPerUpdate by Time.deltaTime in Update. Apart from this detail, I do not see any issue in your code. Keep it up! :slight_smile:


See also:

1 Like

Hi, Nina, thanks for the help, unfortunately it does not work this way, because if you multiply movingStepPerUpdate for Time.deltaTime, that is in seconds and less then 1 as a float we got very tiny steps so the obstacle not moving at all at least visually. I have tried anyway and yes it does not move. Anyway thanks again for your response. Cheers.

You are right. Of course, movingStepPerUpdate should get increased if you multiply by Time.deltaTime. I just figured I should suggest that because “On the screen it works without significant issues and quite smooth” reads as if the movement was not as smooth as it could have been. If you are happy with the current result, keep your code as it is. :slight_smile:

1 Like

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms