- Home /
How can I add or subtract from a variable in a Mathf.Clamp sequence?
I have a 2D slingshot working in my game so that when the player clicks on the character, pulls them back and releases, they are shot into the air. To limit the distance the character can be pulled back I am currently using this section of code:
transform.position.x = Mathf.Clamp(transform.position.x, -35, -28);
transform.position.y = Mathf.Clamp(transform.position.y, 33, 40);
This works fine, but I am planning on having multiple stages and would like to have the distance the character can be pulled set to the same distance every time. It would be nice if I could simply drop in the object the character is launching from and have the code apply no matter where I place it. However, when I try to clamp the distance based on the location of the object, it won't let me. The code I am trying to use for that looks something like this:
transform.position.x = Mathf.Clamp(transform.position.x, (GameObject.Find("spawnPoint") - 5), (GameObject.Find("spawnPoint") + 5);
transform.position.y = Mathf.Clamp(transform.position.y, (GameObject.Find("spawnPoint") - 5), (GameObject.Find("spawnPoint") + 5);
I appreciate any suggestions.
Answer by syclamoth · Jul 09, 2013 at 04:24 AM
Try caching all the data you are using ahead of time. Something like this:
var newPosition : Vector3 = transform.position;
var spawnPoint : GameObject = GameObject.Find("spawnPoint");
Now use 'newPosition' and 'spawnPoint' wherever you would have used the original values, and at the end use
transform.position = newPosition;
to save the changes.
I tried that and it is still giving me the same error. It tells me:
BCE0051: Operater '-' cannot be used with a left hand side of type 'UnityEngine.GameObject' and a right hand side of type 'UnityEngine.Vector3'.
I've also tried setting it up differently. For example:
var $$anonymous$$X = spawnPoint - 5;
if(transform.position.x <= $$anonymous$$X){
transform.position.x = $$anonymous$$X;
}
But this doesn't seem to work either.
Your answer
![](https://koobas.hobune.stream/wayback/20220613105737im_/https://answers.unity.com/themes/thub/images/avi.jpg)