hi everyone, I’m doing some simple 2d tests.
i have a character moving horizontally on a tilemap with 2d collider tilemap.
my player has a box collider 2d and a rigid body 2d.
I have a problem, when I move the character horizontally it starts to rotate. so I blocked the z rotation and the y position, but at this point after a couple of movements the player doesn’t move anymore, I have to stop pressing the movement commands and start again, only in this way the player starts moving again.
what can I do?
I am attaching the configurations for the box collider and the rigid body and the script for movement.
Thank you
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Hero : MonoBehaviour
{
Rigidbody2D rigidbody2d;
float horizontal;
// Start is called before the first frame update
void Start()
{
rigidbody2d = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
horizontal = Input.GetAxis("Horizontal");
}
void FixedUpdate()
{
Vector2 position = rigidbody2d.position;
position.x = position.x + 3.0f * horizontal * Time.deltaTime;
rigidbody2d.MovePosition(position);
}
}
Check if the RB is perhaps falling asleep and prevent it from doing so? It shouldn’t as long as you’re calling MovePosition() but that’s the only thing I can think of.
Beyond that, use Debug.Log() and make sure the code you think is running is still feeding new positions in.
It’s probably catching the corners of individual tile physics shapes. Physics shapes such as polygons including boxes placed side-by-side do not form a continuous surface to the physics system. This is common on all physics systems and produces what is known as ghost collisions.
Only individual physics shapes produce a continuous surface. This is why multi-edge surfaces should use the EdgeCollider2D which produces continuous unlimited numbers of edges. It’s also why devs often use the CompositeCollider2D in Outline (edge) mode with the TilemapCollider2D to convert all those tile polygons into continuous surface edges that are seamless.
What is likely happening is that you hit the corner/side of a physics shape which causes your character to move up and/rotate. By constraining rotation, it has nowhere it can go so like stops as it hits the side of the shape.
Thanks for the reply.
I entered the log.
in case the player starts to rotate (when the rotation is not set) the position is updated, but in fact it rotates.
when I set the rotation z and the character stops the position does not update, but the script continues to log, the log time changes
Then you’re not using Outline mode and likely still using Polygon mode. There’s no difference when it comes to the physics engine which only understands circles, capsule, polygons and edges. Composite in outline is identical to what the EdgeCollider2D puts out: Edges.
The physics engine doesn’t know anything about Unity, nevermind a Collider2D.