Hi,
I’m working on building the movement system for a top down view 2D base defense game, I’ve built a very basic prototype which is pretty much just a blue circle that can be moved via changing velocity using WASD and a wall to test movement and colliders. I’ve got a couple of issues that i can’t seem to solve:
-
The player object keeps moving half into the wall when the button is held down, and used to go all the way through sometimes before I applied a fix to stop it. (This fix doesn’t work perfectly, however - see problem 2)
-
I applied a fix to stop the player object going through the wall by using an overlapCircle transform to tell when it was touching a wall and stop it moving when it was, but I get this weird stuttering effect when I try and move my object into the wall.
My player object has a circle collider which supposedly covers the whole sprite, and the rigidbody2d component is set to interpolate and has continuous collision detection, same as the wall. Is there any way I can make it just stop moving when it hits the wall? I’ve included the code for my player’s movement below.
using UnityEngine;
using System.Collections;
public class SpriteMovementScript : MonoBehaviour
{
public float maxSpeed = 5;
bool wallCollision;
public Transform wallCheck;
float wallRadius = 1;
float speedRecord;
public LayerMask whatIsWall;
// Use this for initialization
void Start()
{
}
// Update is called once per frame
void FixedUpdate()
{
wallCollision = Physics2D.OverlapCircle(wallCheck.position, wallRadius, whatIsWall);
if (wallCollision == true)
{
maxSpeed = 0;
} else
{
maxSpeed = 5;
}
float h = Input.GetAxis("Horizontal");
float v = Input.GetAxis("Vertical");
GetComponent<Rigidbody2D>().velocity = new Vector2(maxSpeed * h, maxSpeed * v);
}
}