Question by
Arun_W_K · May 15 at 09:42 PM ·
2d-gameplaytop down shooter
Stop Player character from moving inside wall (Raycast Teleport to new Position)
Hi there, I am making a top down game where the player moves by shooting a projectile. Using Raycast I have am able to move the character but now the player moves over the walls and does inside them. How can i stop this.
void Update()
{
if(Input.GetButtonDown("Fire1"))
{
Shoot();
}
}
void Shoot()
{
GameObject projectile = Instantiate(_projectilePrefab,_firepoint.position,_firepoint.rotation);
Rigidbody2D rb = projectile.GetComponent<Rigidbody2D>();
rb.AddForce(_firepoint.right *_projectileForce,ForceMode2D.Impulse);
RaycastHit2D hit = Physics2D.Raycast(_firepoint.position,_firepoint.right,100,_wall);
if(hit.collider!=null)
{
if(hit.collider.CompareTag("Wall"))
{
Debug.Log($"Hit");
_rb.MovePosition(hit.point);
}
}
}
Comment