- Home /
Detecting the Edge of the Screen - Object is Flickering
Hi am developing a simple Space Shooter styled 2D game and I am stuck at the point where the Object should restrict itself moving beyond the left and right edges of the screen.
I implemented @Waz solution in one of the answers and it works great if the object is not a rigidbody. However if it is applied to a rigidbody, the object starts to flicker. Below is the code that I used from @Waz
float speed = 0.1f;
Vector3 viewPos = Camera.main.WorldToViewportPoint(transform.position);
viewPos.x = Mathf.Clamp01(viewPos.x);
viewPos.y = Mathf.Clamp01(viewPos.y);
transform.position = Camera.main.ViewportToWorldPoint(viewPos);
I am not sure how to modify the above code so that the object I touch and move does not flicker and even though the speed is 0.1f the object moves very fast when I touch and drag it, I am not sure if this issue is related to the above one but any help would be great.
Answer by LeonineStudios · Feb 04, 2014 at 04:49 PM
I had a similar problem early today. To fix it, I moved my clamp to FixedUpdate() as opposed to Update().
See if that works.
Thanks @LeonineStudios. The flickering disappeared but the other issue continues. The object is moving very fast even I give the speed as 0.01f. Any idea on this? $$anonymous$$y entire code is:
public float speed = 0.01f;
void FixedUpdate () {
if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.$$anonymous$$oved)
{
//The below four lines of code will make sure that the object does not move out of the screen.
Vector3 viewPos = Camera.main.WorldToViewportPoint(transform.position);
viewPos.x = $$anonymous$$athf.Clamp01(viewPos.x);
viewPos.y = $$anonymous$$athf.Clamp01(viewPos.y);
transform.position = Camera.main.ViewportToWorldPoint(viewPos);
Vector2 touchDeltaPosition = Input.GetTouch(0).deltaPosition;
transform.Translate(touchDeltaPosition.x * speed, 0, 0);
}
}
@robertbu - I can see it in line 13. Do you think there is something wrong in that line of code to use the speed?
transform.Translate(touchDeltaPosition.x * speed, 0, 0);
Your answer
