Sprite is outside of Collision box when in play mode
Hello,
I am 1 studying Unity and currently following a 2D tutorial on Unity Learn.
My sprite is supposed to be inside a collider2D box and it is fine when it is in Scene View:
But when I enter Play mode it becomes:
As can be seen the sprite is half way out of the box and make the character out of its intended position when in Play mode.
Here is my Sprite setting:
Mesh type: Full Rect PPU: 120 Pivot: Center Generate Physics Shape: Yes
Prefab: Box Collider 2D:
Auto Tiling: Yes Offset: X = 0, Y = 0;
Rigidbody 2D: Simulated: Yes Gravity Scale: 0 Freeze Rotation: Z
Script:
public float speed;
public float changeTime = 1.0f;
public bool vertical;
Rigidbody2D rigidbody2D;
Animator animator;
float timer;
int direction = 1;
bool broken = true;
void Start()
{
rigidbody2D = GetComponent<Rigidbody2D>();
timer = changeTime;
animator = GetComponent<Animator>();
}
void Update()
{
if(!broken)
{
return;
}
timer -= Time.deltaTime;
if ( timer < 0)
{
direction = -direction;
timer = changeTime;
}
}
void FixedUpdate()
{
if(!broken)
{
return;
}
Vector2 position = rigidbody2D.position;
if (vertical)
{
animator.SetFloat("Move X", 0);
animator.SetFloat("Move Y", direction);
position.y = position.y + Time.deltaTime * speed * direction;
}
else
{
animator.SetFloat("Move Y", 0);
animator.SetFloat("Move X", direction);
position.x = position.x + Time.deltaTime * speed * direction;
}
rigidbody2D.MovePosition(position);
}
void OnCollisionEnter2D (Collision2D other)
{
RubyController controller = other.gameObject.GetComponent<RubyController>();
if(controller != null)
{
controller.changeHealth(-1);
}
}
public void Fix()
{
broken = false;
rigidbody2D.simulated = false;
animator.SetTrigger("Fixed");
}
image1.png
(71.4 kB)
image2.png
(37.5 kB)
Comment
Your answer
![](https://koobas.hobune.stream/wayback/20220613012226im_/https://answers.unity.com/themes/thub/images/avi.jpg)