- Home /
Why this c# program can not to auto die player
I want to make game of tank but I can not auto die player Ex. if three "Bullet" clash to the player, player was dead Where is wrong?
using UnityEngine;
using System.Collections;
namespace StateMachineSample
{
public class PlayerController : MonoBehaviour
{
public Transform turret;
public Transform muzzle;
public GameObject bulletPrefab;
private int maxLife = 3;
private int life;
private float force = 100f;
private float maxSpeed = 30f;
private float maxAngularVelocity = 360f;
private float attackInterval = 0.8f;
private int groundLayerMask;
private float lastAttackTime;
private void Start()
{
groundLayerMask = 1 << LayerMask.NameToLayer("Ground");
}
private void Update()
{
UpdateTank();
UpdateTurret();
}
private void UpdateTank()
{
Vector3 velocity = GetComponent<Rigidbody>().velocity;
life = maxLife;
if (velocity.sqrMagnitude < 1f)
{
return;
}
Vector3 direction = new Vector3(velocity.x, 0f, velocity.z);
Quaternion targetRotation = Quaternion.LookRotation(direction);
transform.rotation = Quaternion.RotateTowards(transform.rotation, targetRotation, maxAngularVelocity * Time.deltaTime);
}
public void TakeDamage()
{
life--;
if (life <= 0)
{
Destroy(gameObject);
}
}
private void UpdateTurret()
{
life--;
if (life <= 0)
{
Destroy(gameObject);
}
// マウス位置を狙う
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, Mathf.Infinity, groundLayerMask))
{
turret.rotation = Quaternion.LookRotation(hit.point - turret.position);
}
// マウス左クリックで発射する
if (Input.GetMouseButtonDown(0))
{
if (Time.time > lastAttackTime + attackInterval)
{
Instantiate(bulletPrefab, muzzle.position, muzzle.rotation);
lastAttackTime = Time.time;
}
}
}
private void FixedUpdate()
{
float x = Input.GetAxisRaw("Horizontal");
float z = Input.GetAxisRaw("Vertical");
Vector3 direction = new Vector3(x, 0f, z).normalized;
GetComponent<Rigidbody>().AddForce(direction * force);
GetComponent<Rigidbody>().velocity = Vector3.ClampMagnitude(GetComponent<Rigidbody>().velocity, maxSpeed);
}
}
}
Answer by ananasblau · Oct 29, 2016 at 04:49 PM
Where is wrong? indeed. You have both FixedUpdate()
and Update()
, not sure if that is a great idea.
In UpdateTank()
you have life = maxLife;
which means with every Update()
you are resetting the player's life. Remove the line and you should be good (or rather: dead).
can you type me correct program? because I remove the life = maxlife; to start but it still do not work correct (the player vanish but the bullet did not crash)
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Serializable class definition in base class doesn't show in editor 1 Answer
How to make buttons have sound when it is highlighted and clicked? 0 Answers
Updating Unity 2 Answers