- Home /
Hi,How do I make a 2D laser beam with stable speed ?
I create an olinegame about guys with laser beams in the room ,so i decide to make my laser beam by rigidbody2d that reflect with everything in the room , but when i test it .Sometime my laser has lower speed and stop moving.
what should i do to improve my laser better ?
-laser beam is 2d circle collider with physics2d bounce 0.5
my laser beam code :
public class LaserBehavior : MonoBehaviour {
// Use this for initialization
Rigidbody2D _rbLaser;
[SerializeField]
GameObject _laser = null;
public float _speedLaser;
/*
void Awake()
{
_rbLaser = gameObject.GetComponent<Rigidbody2D>();
//Invoke("LaserControll",0.1f);
}
*/
void Start () {
_rbLaser = gameObject.GetComponent<Rigidbody2D>();
Invoke("LaserControll",0.1f);
}
// Update is called once per frame
void Update () {
}
void LaserControll()
{
Vector2 direction = new Vector2(Random.Range(-2, 2), Random.Range(-3, 2)+1);
_rbLaser.AddRelativeForce(direction*_speedLaser,ForceMode2D.Impulse);
}
void OnCollisionEnter2D(Collision2D other)
{
if (other.gameObject.tag == "Player")
{
other.gameObject.GetComponent<SpriteRenderer>().color = Color.black;
other.gameObject.GetComponent<SpriteRenderer>().color = Color.green;
Debug.Log("destroy");
Destroy(this);
}
if (other.gameObject.tag == "Shield")
{
Vector2 inDirect = GetComponent<Rigidbody2D>().velocity;
Vector2 inNormal = other.contacts[0].normal;
Vector2 reflect = Vector2.Reflect(inDirect, inNormal);
reflect.Normalize();
_rbLaser.AddRelativeForce(reflect * _speedLaser, ForceMode2D.Impulse);
}
if (other.gameObject.tag == "ReflectObject")
{
//Debug.Log("REFLECT " +other.gameObject.name);
//Invoke("LaserControll", 0.1f);
Vector2 inDirect = GetComponent<Rigidbody2D>().velocity;
Vector2 inNormal = other.contacts[0].normal;
Vector2 reflect = Vector2.Reflect(inDirect,inNormal);
reflect.Normalize();
//Debug.Log("inDirection " + inDirect);
// Debug.Log("REFLECT " + other.gameObject.name+" inNormal" + inNormal);
//Debug.Log("reflect" + reflect);
// _rbLaser.AddRelativeForce(reflect *(_speedLaser*10), ForceMode2D.Force);
_rbLaser.AddRelativeForce(reflect * _speedLaser, ForceMode2D.Impulse);
if (_laser != null)
{
GameObject go = Instantiate(_laser, transform.position, transform.rotation);
go.name = "Laser";
go.GetComponent<SpriteRenderer>().color = Color.white;
}
}
}
}
What happens when you replace AddRelativeForce
with just AddForce
?
@HomebrewAI I want to use my laser local position to control direction ,so i choose addRelativeForce .
Answer by xxmariofer · Jan 31, 2019 at 09:46 AM
hello, if the beam is a object that is losing speed, try going into the laser rigidbody propertys and set drag and angular drag to 0, also the walls (and i think the rigidbdy too) must have a Physical Material attach to it with the bounciness set to max.