Hey, I’m doing a 2d Platform Game to train my unity skills (I’m new), When I stomp on them they will die, and when I touch them (not from above) the player will die. And I need help, so here’s the script if you want to help me!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Enemy : MonoBehaviour
{
public LayerMask enemyMask;
public float speed = 1;
Rigidbody2D myBody;
Transform myTrans;
float myWidth;
private GameManager gameManager;
void Start()
{
myTrans = this.transform;
myBody = this.GetComponent<Rigidbody2D>();
myWidth = this.GetComponent<SpriteRenderer>().bounds.extents.x;
gameManager = FindObjectOfType<GameManager>;
}
void FixedUpdate()
{
Vector2 lineCastPos = myTrans.position - myTrans.right * myWidth;
bool isGrounded = Physics2D.Linecast(lineCastPos, lineCastPos + Vector2.down, enemyMask);
if(!isGrounded)
{
Vector3 currRot = myTrans.eulerAngles;
currRot.y += 180;
myTrans.eulerAngles = currRot;
}
//Always move forward
Vector2 myVel = myBody.velocity;
myVel.x = -myTrans.right.x *speed;
myBody.velocity = myVel;
}
void OnCollisionEnter2d(Collision2D coll)
{
if(coll.gameObject.tag == "Player")
{
gameManager.Respawn ();
}
}
void OnTriggerEnter2D(Collider2D other)
{
if(other.tag == "Player")
{
if (other.GetComponent<Rigidbody2D> ().velocity.y <= 0f)
{
other.GetComponent<Rigidbody2D>().velocity = new Vector2 (rb2d.velocity.x, other.GetComponent<PlayerMovement>().jumpspeed);
Destroy (gameObject);
}
}
}
}