What did I do wrong? Ship just flickers between both limits at once!

I attempted the challenge and came up with what I thought was the answer, but it didn’t work, so I thought Ben would address the problem in the solution, but to my surprise, his implementation seems to be exactly the same as mine, but mine does this:

*no input is being pressed…
ezgif.com-optimize (1)
(For the life of me can’t figure out why this shows so small.)

On my actual monitor, to the naked-eye, it looks like the ship is constantly in both places at once, it’s just that the dropped frames and framerate of this gif show it sticking a few times.

Here’s my code. What am I not seeing that I did wrong?

using UnityEngine;
using UnityStandardAssets.CrossPlatformInput;

public class Player : MonoBehaviour
{
    [Tooltip("In ms^-1")] [SerializeField] float xSpeed = 10f;
    [Tooltip("+/- value")][SerializeField] float xLimit = 3.9f;

    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        float xThrow = CrossPlatformInputManager.GetAxis("Horizontal");
        float xOffset = xThrow * xSpeed * Time.deltaTime;

        float rawXPos = transform.localPosition.x + xOffset;
        float clampedXPos = Mathf.Clamp(rawXPos, -xLimit, xLimit);
        transform.localPosition = new Vector3(clampedXPos, transform.localPosition.y, transform.localPosition.z);
    }
}

Hi,

Please log a few variables into your console, e.g. xLimit and whatever you feel could be part of problem.

Are the values the expected ones?

I was logging stuff until I got the numbers where I wanted, so deleted them before doing the Clamp part.

So this is weird. It’s now working, except that my code is literally identical to how it was when it wasn’t working:


diffcheck_2

Turns out my code works as intended, but I have no idea why it decided to not work for a while.

Well, it’s not that uncommon that Unity suddenly behaves in a strange way. Restarting often magically fixes things.

If the issue does not reoccur, do not worry about it anymore. Your code looks fine.

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

Privacy & Terms