Problem with math clamp

hi!
i was trying yo use the mathf. clamp to restrict the movement, but instead of restrict the position according to the local position, it radically move it to another place of the map ( with the coordinates of the range). i have checked the timeline and the code, and the problem is in the matf.clamp function and i still dont know exactly why it doesnt work

thanks in advance

code:

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

public class Movement : MonoBehaviour
{

[SerializeField] float speedControl;
[SerializeField] float xRange = 5f;
[SerializeField] float yRange = 3.5f;






// Update is called once per frame
void Update()
{
	//PlayerControls//
	float horizontalMovement = Input.GetAxis("Horizontal");
	float verticalMovement = Input.GetAxis("Vertical");
    
    
	//Movement//
	float xOffset= horizontalMovement * Time.deltaTime * speedControl;
	float xPos = transform.localPosition.x + xOffset;
	float clampedX = Mathf.Clamp(xPos, -xRange,xRange);

	
    
    
    
	float yOffset = verticalMovement * Time.deltaTime * speedControl;
	float yPos = transform.localPosition.y + yOffset;
	float clampedY = Mathf.Clamp(yPos, -yRange,yRange);
	

	transform.localPosition =  new Vector3( clampedX, clampedY,transform.localPosition.z);
    
}

}

Hi @ginopalacios,

Welcome to our community! :slight_smile:

Please note, it’s better to copy/paste your code and apply the code fencing characters, rather than using screenshots. Screenshots are ideal for displaying specific details from within a game engine editor or even error messages, but for code, they tend to be less readable, especially on mobile devices which can require extensive zooming and scrolling.

You also prevent those that may offer to help you the ability to copy/paste part of your code back to you with suggestions and/or corrections, meaning that they would need to type a potentially lengthy response. You will often find that people are more likely to respond to your questions if you make it as easy as possible for them to do so.

Regarding your problem, have you already tried to add Debug.Logs to your code to see what is going on during runtime? And did you move the spaceship manually in the scene to see if the values for the clamping make sense?

Hope this helps :slight_smile:


See also;

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

Privacy & Terms