Reputation: 65
I made 2D wall in Unity, but my character can walk through it. What's wrong? My character has Rigibody2D and BoxCollider2D, wall has box collider. Code of character movement:
Vector2 moveVec = new Vector2(CrossPlatformInputManager.GetAxis("Horizontal"),CrossPlatformInputManager.GetAxis("Vertical"));
moveVec = moveVec * moveForce;
transform.Translate (moveVec);
Upvotes: 1
Views: 163
Reputation: 125245
My character has Rigibody2D and BoxCollider
If you use Rigibody2D
, you must also use BoxCollider2D
not BoxCollider
. Make sure the wall has it's BoxCollider2D
too.
No collision when transform.Translate
or transform.position
is used to move an Object. If your GameObject has Rigidbody2D
attached to it, then it must be moved with Rigidbody2D.velocity
, Rigidbody2D.AddForce
(Rigidbody2D.AddXXX
) or Rigidbody2D.MovePosition
.
It is better to do this particular thing in the FixedUpdate()
function. Also, I think GetAxisRaw
should be used instead of GetAxis
so that the player will stop immediately the key/finger is released.
public float speed = 2f;
Rigidbody2D rg2d;
void Start()
{
rg2d = GetComponent<Rigidbody2D>();
}
void FixedUpdate()
{
float h = CrossPlatformInputManager.GetAxisRaw("Horizontal");
float v = CrossPlatformInputManager.GetAxisRaw("Vertical");
Vector2 tempVect = new Vector2(h, v);
tempVect = tempVect.normalized * speed * Time.fixedDeltaTime;
rg2d.MovePosition((Vector2)transform.position + tempVect);
}
You can always decrease/increase the speed if it moves too fast/slow.
Upvotes: 2