I have a simple top-down control scheme that checks whenever the left mouse button is pressed, and then uses Vector3.MoveTowards to move the player to that location. However, I cannot get collision to work with this method - in other words, the player walks straight through everything.
I tried scripting it with OnCollisionEnter, making the player stop and move slightly outside the object he collides with, every time he collides with something - but it doesn’t seem to detect the collision whatsoever, despite both objects having colliders. What am I doing wrong?
Simple objects aren’t constrained by collisions, only CharacterControllers or Rigidbodies. Since Rigidbodies are too complicate to control, you should add a CharacterController to the object and move it with Move or SimpleMove.
you can convert it to use a CharacterController with a code like this:
// find the target position relative to the player:
var dir: Vector3 = targetPos - transform.position;
// calculate movement at the desired speed:
var movement: Vector3 = dir.normalized * speed * Time.deltaTime;
// limit movement to never pass the target position:
if (movement.magnitude > dir.magnitude) movement = dir;
// move the character:
GetComponent(CharacterController).Move(movement);
The CharacterController is constrained by collisions. If there’s an obstacle between it and targetPos, this code will make the CharacterController slip along the obstacle looking for the smaller distance to the targetPos, what may make it avoid round or inclined obstacles - but an obstacle big enough or perpendicular enough to the trajectory can stop it.
NOTE: The CharacterController is a special capsule collider aligned to the Y axis. You can reduce its height to make it spherical, but there’s no way to transform it in a cubic collider, nor rotate it to become horizontal. This restriction may complicate using it in cars, boats or other objects that can’t fit reasonably into a capsule or sphere.
I had this problem last week, for me it was a case of moving too fast so it was being moved to the other side of the wall and effectively “going through” the wall. I think it’ll work if you use a slower speed to move the object or if you use Quaternion.LookRotation(x-y) and add a force to the rigidbody on it.
As a side note, I gave up on the game because I couldn’t get useful data out of the mouse position (using Camera.ScreenToWorldPoint) so I would be really gratefull if you could give me some code for that bit