Tiny Problem

So im making a 2D space game where i want the enemy to start from a certian point, move one unit every second for a cycle and then reverse back to the same position in the same way

float timeElapsed;
    [SerializeField] int cycleTime;
    [SerializeField] int distanceTravelledPerCycle;

    void Update()
    {
        int timeElapsedRounded = Mathf.RoundToInt(timeElapsed);
        timeElapsed += Time.deltaTime;

        if(timeElapsed < cycleTime)
        {
            if(timeElapsed >= timeElapsedRounded)
            {
                float xPos = transform.position.x + distanceTravelledPerCycle;
                float yPos = transform.position.y;
                
                transform.position = new Vector2(xPos, yPos);
            }
        }
    }

This doesnt work
I want it to work like this

ezgif.com-video-to-gif-converted

I’m not sure what the purpose is of timeElapsedRounded, it will always be less than timeElapsed because you’re adding Time.deltaTime immediately after setting the rounded value. The second if check will always return true as a result.

The following should get the enemy moving once per cycle in a single direction.

    float timeElapsed;
    [SerializeField] int cycleTime;
    [SerializeField] int distanceTravelledPerCycle;

    void Update()
    {
        timeElapsed += Time.deltaTime;

        if(timeElapsed < cycleTime) { return; }

        float xPos = transform.position.x + distanceTravelledPerCycle;
        float yPos = transform.position.y;
                
        transform.position = new Vector2(xPos, yPos);
        timeElapsed = 0f;
    }

After that, to move it back in the opposite direction, you can either do a position check or a second timer to change xPos to negative.

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

Privacy & Terms