- Home /
object in Jump&Run-Game is flickering when hitting boundaries - how to avoid?
I'm trying to create a 3D-Jump&Run-Game but I have this issue with the flickering. My assumption was that since the player's pivot is clamped to the borders, half of the player leaves the boundaries (reason for flickering).
So I did this (but unfortunately it is not working) :
public class PlayerController : MonoBehaviour {
Rigidbody myRigidbody;
public float speed = 6f;
/* variables to limit movement range in x-axis
* border values determined by visual estimate in scene view
* issue: the player's pivot is clamped to the borders --> half of the player leaves the border -->
flickering
* modify border values and add/substract half of the player's size (done in RunHandler())
*/
float objectWidth;
float minX = -1.601f;
float maxX = 1.671f;
void Start()
{
//compute player's size and devide it by 2 --> for keeping gameobject within boundaries
objectWidth = transform.GetComponent<MeshRenderer>().bounds.size.x / 2;
myRigidbody = GetComponent<Rigidbody>();
}
void FixedUpdate()
{
RunHandler();
}
void RunHandler()
{
float moveVertical = Input.GetAxis("Vertical");
float moveHorizontal = Input.GetAxis("Horizontal");
Vector3 movement = new Vector3(moveHorizontal, 0f, moveVertical);
myRigidbody.MovePosition(transform.position + (movement * speed));
/*
* set a variable to the position
* modify the variable to keep x within minX and maxX
* set the transform position to the modified vector
*/
Vector3 currentPosition = transform.position;
currentPosition.x = Mathf.Clamp(currentPosition.x, minX + objectWidth, maxX - objectWidth);
transform.position = currentPosition;
}
}
Answer by LeFlop2001 · Jun 18, 2020 at 10:59 PM
Why not just use Colliders as boundaries
Dear @LeFlop2001 thank you very much for your response and your help!!
I know, I could create invisible walls to solve this issue but I'd like to programm it.. There has to be a possible way similar to the execution of keeping the player within screen boundaries.
Thanks again :) and have a great weekend
Answer by tadadosi · Jun 20, 2020 at 02:34 PM
When you are dealing with physics using a rigidbody, never use transform.position unless you set your rigidbody to kinematic and zero out its velocity.
To fix your problem you need to change all your transform.position
to myRigidbody.position
.