Java to c# fall damage
hi since i dont know coding very well and i'm learning can please someone convert this java code to c# to work on unity 5?
pragma strict
var lastPositionY : float = 0f; var fallDistance : float = 0f; var player : Transform;
private var controller : CharacterController;
var currentHealth : float = 10.0f;
function Start() { controller = GameObject.Find("First Person Controller").GetComponent(CharacterController); }
function Update () {
if(lastPositionY > player.transform.position.y) { fallDistance += lastPositionY - player.transform.position.y; }
lastPositionY = player.transform.position.y;
if(fallDistance >= 5 && controller.isGrounded)
{
currentHealth -= 5;
ApplyNormal();
}
if(fallDistance <= 5 && controller.isGrounded)
{
ApplyNormal();
}
}
function ApplyNormal() { fallDistance = 0; lastPositionY = 0; }
function OnGUI() { GUI.Box(Rect(10, 20, 50, 20),"" + currentHealth); }
Answer by TBruce · Aug 19, 2016 at 07:01 PM
I had to use an arbitrary class name/file name of PlayerFallManager since you did not provide one, but here is your code converted. Change the name to what you like (file name and class name must match)
using UnityEngine;
using System;
public class PlayerFallManager : MonoBehaviour
{
public float lastPositionY = 0f;
public float fallDistance = 0f;
public Transform player;
CharacterController controller;
public float currentHealth = 10.0f;
public void Start()
{
controller = GameObject.Find("First Person Controller").GetComponent<CharacterController>();
}
public void Update()
{
if(lastPositionY > player.transform.position.y)
{
fallDistance += lastPositionY - player.transform.position.y;
}
lastPositionY = player.transform.position.y;
if(fallDistance >= 5 && controller.isGrounded)
{
currentHealth -= 5.0f;
ApplyNormal();
}
if(fallDistance <= 5 && controller.isGrounded)
{
ApplyNormal();
}
}
public void ApplyNormal()
{
fallDistance = 0.0f; lastPositionY = 0.0f;
}
public void OnGUI()
{
GUI.Box(new Rect(10.0f, 20.0f, 50.0f, 20.0f),"" + currentHealth);
}
}
many many thanks...work like a charm as standalone and with a bit of effort i managed to integrate it in my Player.cs script..
and learned the similarities between C# and Js...
many thanks again...