I want to drag a player object to throw coming obstacles in the way. For this purpose, I require to hold the player object and using it, I require to hit upcoming obstacles in the gameplay.
Basically currently I am working on this type of gameplay:
At present I am trying to hit obstacles using this setup:
void Update()
{
Vector2 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Rigidbody2D.position = mousePos;
}
Here are the inspector settings:
Still, the player hitting is jerky or not smooth. Multiple times obstacles get fixed within a player object.
So how to make this hitting proper?
You’re just teleporting the Rigidbody2D from position to position instantly and doing that per-frame. I can only assume then that you’re also running the physics simulation during the fixed-update and not per-frame so it runs at the stock fixed-frequency. Instantly setting the position of a Rigidbody2D just means you’re potentially just causing overlaps with other colliders (it isn’t actually moving at all, just appearing in new positions like a teleport) when the sim runs and it also means you won’t get per-frame interpolation either as you’re just stomping over its position.
If you want to “drag” a Rigidbody2D/Collider then you should consider either using Rigidbody2D.MovePosition (with interpolation on) which is actioned when the sim runs or use the TargetJoint2D and configure how fast it moves etc.
I have a GitHub project which shows a lot of the 2D physics working here. It uses a lot of dragging and following the mouse but there’s also a specific scene showing following the mouse with the TargetJoint2D here.
1 Like