I was making a ball bouncing off a wall but it did not work.
Can someone help me?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BounceOFF : MonoBehaviour
{
private bool isPressed;
private Rigidbody2D objectRigidbody;
private Vector2 newThing;
// Start is called before the first frame update
private void Awake()
{
objectRigidbody = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.E))
{
isPressed = true;
}
}
private void FixedUpdate()
{
Vector2 addForcing = new Vector2(8, 0);
// if player press E then add force
if (isPressed)
{
objectRigidbody.AddForce(addForcing, ForceMode2D.Impulse);
isPressed = false;
}
}
private void OnCollisionEnter2D(Collision2D collision)
{
// Why this code doesnt work?
if (collision.collider.name == "Square")
{
Vector2 inNormal = collision.contacts[0].normal;
newThing = Vector2.Reflect(objectRigidbody.velocity, inNormal);
objectRigidbody.velocity = newThing;
}
}
}