- Home /
clamp input.acclereation within screen width
I'm making a game where you should move your player on an android device by using the input.acclereation functtion. The player moves only on the x.axis, it works good. My problem is, that the player is running out of the screen on left and right side of the x axis. I tried to clamp the movement to the screen width, it works either but not very smoothly. If the player touches the screen border and you want to go to the other side it jumps from the wall instead from moving to the other site.
Here ist my code:
float targetSpeed;
targetSpeed = Mathf.Clamp (Input.acceleration.x, -0.25f, 0.25f);
Vector3 ObjectScreenPosition = Camera.main.WorldToScreenPoint (transform.position);
float maxwidthRight = (Screen.width - 30);
float maxwidthLeft = (Screen.width - Screen.width + 57);
if (ObjectScreenPosition.x >= maxwidthRight) {
targetSpeed = Mathf.Clamp (Input.acceleration.x, -0.2f, 0f);
} else if (ObjectScreenPosition.x <= maxwidthLeft) {
targetSpeed = Mathf.Clamp (Input.acceleration.x, -0f, 0.2f);
}
transform.Translate (targetSpeed * speed * 145, transform.position.y, transform.position.z);
Do you have any sugestions for me to do it in a better way ? Or an idea to fix my "bounce" problem ? Thanks !
Well, first off, your line
float maxwidthLeft = (Screen.width - Screen.width + 57);
can be simplified with
float maxwidthLeft = 57;
Because (Screen.width-Screen.width) = 0
Beyond that though, your code largely makes sense and should work... Can you maybe post a video of what is happening so we can get a better idea?
Thanks, i changed the code for the width = 57 ;-) I'll try to do a video an will upload it soon.
Not sure if this is related to your problem, but you probably don't want to use the transform.position value in transform.Translate in your code:
transform.Translate (targetSpeed * speed * 145, transform.position.y, transform.position.z);
$$anonymous$$aybe you meant to do this:
transform.Translate (targetSpeed * speed * 145, 0, 0);
Answer by angryFlo · May 05, 2016 at 06:50 PM
The Problem is solved, i changed three things. 1. Changeds the suggestions from FortisVenaliter 2. Changeds the suggestions from fabian.mkv 3. I added this code in the start section of my script: transform.position = new Vector3 (0, 0, 0);
Maybe one of these or alle three together fixes the problem, thanks for help.
Answer by angryFlo · May 05, 2016 at 05:23 PM
Thanks for the suggestions i'll figure out your code and will give an Update.