c# - Using Mathf.Clamp in unity for boundries -
i making 2d space shooter mobile game. trying set boundary ship not go out of screen. can move ship tilting phone. have shipcontroller.cs attached ship object. , fixedupdate function:
public float xmin, xmax, ymin, ymax; void fixedupdate() { //tilt move ship transform.translate(input.acceleration.x * speed, input.acceleration.y * speed, 0); //create boundries rigidbody2d.position = new vector2( mathf.clamp(rigidbody2d.position.x, xmin, xmax), mathf.clamp(rigidbody2d.position.y, ymin, ymax) ); }
the min , max values defined in unity inspector. code works great if testing on pc. when exporting phone, motion jittery , glitches. ship boundary , kind of start jumping. motion when tilting not smooth. there other way create smoother?
try changing code update
instead of fixedupdate
. i'm guessing there multiple updates called between fixed updates. reason ship getting first on boarder @ multiple frames , returned @ next fixed update.
when using update
, need handle delta time yourself. otherwise speed different in different fps. can done multiplying speed deltatime
:
public float xmin, xmax, ymin, ymax; void update() { //tilt move ship transform.translate(input.acceleration.x * speed * time.deltatime, input.acceleration.y * speed * time.deltatime, 0); //create boundries transform.position = new vector2( mathf.clamp(transform.position.x, xmin, xmax), mathf.clamp(transform.position.y, ymin, ymax) ); }
after multiplying deltatime
value of speed
way small. need utilize time find proper value again.
c# unity3d boundary
No comments:
Post a Comment