- Home /
Question by
pankajpomal · May 05, 2018 at 10:04 AM ·
gameobjectgamedestroy object
My ship destroyed when i press fire
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class PlayerController : MonoBehaviour { public float speed = 15.0f; public float padding = 1f; public GameObject laser; public float projectileSpeed; public float firingrate = 0.2f; public float health = 250f;
float xmin;
float xmax;
void Start (){
float distance = transform.position.z - Camera.main.transform.position.z;
Vector3 leftmost = Camera.main.ViewportToWorldPoint(new Vector3 (0,0,distance));
Vector3 rightmost = Camera.main.ViewportToWorldPoint(new Vector3 (1,0,distance));
xmin = leftmost.x + padding;
xmax = rightmost.x - padding;
}
void Fire () {
Vector3 offset = new Vector3(0, 1, 0);
GameObject beam = Instantiate (laser, transform.position, Quaternion.identity) as GameObject;
GetComponent<Rigidbody2D> () .velocity = new Vector3 (0, projectileSpeed, 0);
}
void Update ()
{
if (Input.GetKeyDown (KeyCode.Space)) {
InvokeRepeating ("Fire", 0.0001f, firingrate);
}
if (Input.GetKeyUp (KeyCode.Space)) {
CancelInvoke ("Fire");
}
if (Input.GetKey (KeyCode.LeftArrow)){
transform.position += Vector3.left * speed * Time.deltaTime;
}else if (Input.GetKey (KeyCode.RightArrow)) {
transform.position += Vector3.right * speed * Time.deltaTime;
}
// restrict the player to gamespace
float newX = Mathf.Clamp(transform.position.x, xmin, xmax);
transform.position = new Vector3 (newX, transform.position.y, transform.position.z);
}
void OnTriggerEnter2D (Collider2D collider) {
Projectile missile = collider.gameObject.GetComponent<Projectile> ();
Debug.Log ("Player Collided with Missile");
if (missile) {
health -= missile.GetDamage ();
missile.Hit();
if (health <= 0) {
Destroy(gameObject);
}
}
}
}
Comment
Answer by wextia · May 05, 2018 at 10:37 AM
Check that the health value in the inspector is set to something greater than 0. Also, your laser prefab has the projectile component? Your player could be colliding with it.
Your answer
Follow this Question
Related Questions
Rotation help! 1 Answer
getting udp package info inside unity (GlovePIE) 0 Answers
Problem with the algorithm when deleting an object 0 Answers
Populate game objects from a list?? (C#) 1 Answer
Enemy Rotation Problem 1 Answer