Complete C# Unity Game Developer 3D - Argon Assault - Mathf.Clamp issue

When I add Mathf.Clamp to the player object, and then press play to test, the player object will move a load of units to the right on the X Axis.

When I play the timeline, the object doesn’t move to the right on the x AXIS.

Here is the code:

using System;

using System.Collections;

using System.Collections.Generic;

using UnityEngine;

public class PlayerControls : MonoBehaviour

{

[SerializeField] float controlSpeed = 10f;

[SerializeField] float xRange = 5f;



void Update()

{

    float xThrow = Input.GetAxis("Horizontal");

    float ythrow = Input.GetAxis("Vertical");

    float xOffset = xThrow * Time.deltaTime * controlSpeed;

    float rawXPos = transform.localPosition.x + xOffset;

    float clampedXPos = Mathf.Clamp(rawXPos, -xRange, xRange);

    float yOffset = ythrow * Time.deltaTime * controlSpeed;

    float newYPos = transform.localPosition.y + yOffset;

    transform.localPosition = new Vector3 (clampedXPos, newYPos, transform.localPosition.z);

       

}

}

Hi Beeka,

Welcome to our community! :slight_smile:

Did you check the position of the player in the Inspector? And did you log the xRange value into your console to see if there is a difference between the values in your console and the position in the Inspector?


See also:

Hi Nina,

I finally figured it out and was user error.

The Player Rig which the Camera and Player ship was on, was completely off.

I reset all positions and then moved the player rig back to the starting point and then adjusted the camera.

All working fine.

I spoke to a few other people and seems to be a common hiccup.

Thank you for getting back to me.

I’m glad you solved the problem. Thanks for sharing your solution. I’m sure it’ll be helpful for other people. :slight_smile:

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

Privacy & Terms