- Home /
Spikes for a platformer game
I have no idea how to make it so that spikes hurt the player. By the way, here's my code for the player, if that helps. using System.Collections; using System.Collections.Generic; using UnityEngine;
public class Platformer : MonoBehaviour { Rigidbody2D rb;
public float speed;
public float jumpForce;
public float fallMultiplier = 2.5f;
public float lowJumpMultiplier = 2f;
bool isGrounded = false;
public Transform isGroundedChecker;
public float checkGroundRadius;
public LayerMask groundLayer;
public float rememberGroundedFor;
float lastTimeGrounded;
public int defaultAdditionalJumps = 1;
int additionalJumps;
void Start()
{
rb = GetComponent<Rigidbody2D>();
additionalJumps = defaultAdditionalJumps;
}
void Update()
{
Move();
Jump();
BetterJump();
CheckIfGrounded();
}
void Move()
{
float x = Input.GetAxisRaw("Horizontal");
float moveBy = x * speed;
rb.velocity = new Vector2(moveBy, rb.velocity.y);
}
void Jump()
{
if (Input.GetKeyDown(KeyCode.Space) && (isGrounded || Time.time - lastTimeGrounded <= rememberGroundedFor || additionalJumps > 0))
{
rb.velocity = new Vector2(rb.velocity.x, jumpForce);
additionalJumps--;
}
}
void BetterJump()
{
if (rb.velocity.y < 0)
{
rb.velocity += Vector2.up * Physics2D.gravity * (fallMultiplier - 1) * Time.deltaTime;
}
else if (rb.velocity.y > 0 && !Input.GetKey(KeyCode.Space))
{
rb.velocity += Vector2.up * Physics2D.gravity * (lowJumpMultiplier - 1) * Time.deltaTime;
}
}
void CheckIfGrounded()
{
Collider2D colliders = Physics2D.OverlapCircle(isGroundedChecker.position, checkGroundRadius, groundLayer);
if (colliders != null)
{
isGrounded = true;
additionalJumps = defaultAdditionalJumps;
}
else
{
if (isGrounded)
{
lastTimeGrounded = Time.time;
}
isGrounded = false;
}
}
}`
Answer by highpockets · Aug 22, 2020 at 09:03 AM
You don’t have anything related to spikes in this code.
First of all the player either needs a health int/float that you can subtract from or the player immediately has to die when touching the spikes.
Let’s say you are working with a health int and every time the player touches spikes, the player looses a certain amount:
public class PlayerControl : MonoBehaviour
{
private int health = 100;
void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.tag == "Spikes")
{
health -= 25;
if(health <= 0)
//player dies
}
}
}
It’s pretty much as simple as that, if the player should just die immediately then disregard the health altogether and just do whatever you do for a player death immediately when the spikes are touched.
Your answer
Follow this Question
Related Questions
Jumping from special jump orb 1 Answer
My 2D Player Can't Move (2d Photon Game) :(,My Player Don't Move (2d Character Controller 0 Answers
Trying to make the camera follow the player but stop at the edge. 1 Answer
In my 2D platformer game, how would I create a height marker?, 1 Answer
How to check if an object hits the ground hard enough then add explosive force around it (2D) 1 Answer