How to create a reflective shield for my 2D platformer character?
Hi all, as the tile suggests, I'm trying to write a script that will make my character cause enemies to reflect off of them i.e. flip their velocity when they collide. I want to to be an ability if the player holds down the mouse button. There is another answer from 2011: https://answers.unity.com/questions/168454/creating-a-shield.html but it's written in Java and I barely even understand C#! I'll attach the script that I have below.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ReflectShield : MonoBehaviour
{
public float reflectivePower;
private bool active;
// Update is called once per frame
void Update()
{
if(Input.GetMouseButtonDown(0)) {
active = true;
}
}
void OnCollisionEnter2D(Collision2D collision) {
if(active) {
if (collision.gameObject.CompareTag("Enemy")) {
Vector2 dir = collision.gameObject.GetComponent<Rigidbody>().velocity;
dir = -dir;
collision.gameObject.GetComponent<Rigidbody>().velocity = dir * reflectivePower;
}
}
}
}
Answer by streeetwalker · Sep 07, 2020 at 06:56 AM
HI @jpothoof, all you need to do is take the negative of the current velocity and apply it. That is what the code is doing, and it should work (if reflectivePower == 1 then it will be a perfectly elastic "bounce").
So where is the problem?
Your answer
Follow this Question
Related Questions
Collider disabling by itself... 2 Answers
Adding a Highscore to game 1 Answer
Input Command Issues 0 Answers
"Field " " is never assigned to, and will always have it's default value null" 2 Answers