So to preface, I’m scripting this with pretty much no familiarity with C# or Unity. It’s my learner project.
The thing I’m running into is inconsistent bullet behavior related to deflection of the bullets. It seems to be related to something with the physics, but I haven’t been able to figure it out.
The goal is to have a shield that I can move about around the player, and rotates to allow control of the bounce. The issue ends up being that every so often the bullet just seems to lose all momentum (or is imperceptibly moving in place). This happens more frequently when the player is in motion.
Here is my current bullet script for it’s behavior.
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Test_Bullet : MonoBehaviour
{
float moveSpeed = 7f;
Rigidbody2D rb;
playerController target;
Vector2 moveDirection;
private Vector2 lastPos;
private Vector2 velocity;
void Start()
{
rb = GetComponent<Rigidbody2D>();
target = GameObject.FindObjectOfType<playerController>();
moveDirection = (target.transform.position - transform.position).normalized * moveSpeed;
rb.velocity = new Vector2(moveDirection.x, moveDirection.y); //applying movement
Destroy(gameObject, 8f);
}
void Update()
{
Vector3 pos3D = transform.position;
Vector2 pos2D = new Vector2(pos3D.x, pos3D.y);
velocity = pos2D - lastPos;
lastPos = pos2D;
}
private void OnCollisionEnter2D(Collision2D col)
{
Vector3 N = col.contacts[0].normal;
Vector3 V = velocity.normalized;
Vector3 R = Vector3.Reflect(V, N).normalized;
rb.velocity = new Vector2(R.x, R.y) * moveSpeed;
}
}
Think an additional thing that can be noted is the way in which I target the player is bad, but most tutorials want me to orient the bullet and propel it forward that way, which I don’t want to do because I want the sprite fixed facing upwards.
Currently it results in this;