Hi,
I have just started using Unity due to some inspiration for a top-down game.
I have implemented a basic player controller, where you can move in both x-y directions as well as rotate the sprite towards the cursor and a shooting mechanic as well (thanks to Brackeys).
One problem I have encountered is that whenever I move and shoot at the same time the sprite “jitters”, what I can see is that the rotation for the player-gameobject is constantly changing in very small increments around the current rotation value, but after shooting it just returns to the original value like nothing happened. I can’t for the life of me figure out what is going on since the player’s rigidbody is never accessed in the shooting-script.
The bullet in question is instantiated at a FirePoint in front of the character and it has no rigidbody so the bullet can’t collide with the FirePoint.
Some help would be appreciated!
// Brackeys top-down controller
public class PlayerController : MonoBehaviour
{
public float moveSpeed = 5f;
public Rigidbody2D rb;
public Camera cam;
Vector2 movement;
Vector2 mousePos;
// Update is called once per frame
void Update()
{
movement.x = Input.GetAxisRaw("Horizontal");
movement.y = Input.GetAxisRaw("Vertical");
mousePos = cam.ScreenToWorldPoint(Input.mousePosition);
}
void FixedUpdate()
{
rb.MovePosition(rb.position + movement * moveSpeed * Time.fixedDeltaTime);
Vector2 lookDir = mousePos - rb.position;
float angle = Mathf.Atan2(lookDir.y, lookDir.x) * Mathf.Rad2Deg + 90f;
rb.rotation = angle;
}
}
public class Weapon : MonoBehaviour
{
public Transform firePoint;
public GameObject bullet;
// Update is called once per frame
void Update()
{
if (Input.GetButtonDown("Fire1"))
{
Shoot();
}
}
void Shoot()
{
Instantiate(bullet, firePoint.position, firePoint.rotation);
}
}
public class Bullet : MonoBehaviour
{
public float speed = 5f;
public Rigidbody2D rb;
// Start is called before the first frame update
void Start()
{
rb.velocity = transform.right * speed;
}
void OnTriggerEnter2D(Collider2D collision)
{
Destroy(gameObject);
}
void OnBecameInvisible()
{
Destroy(gameObject);
}
}