Help with converting c# to JS

Hello! I’m trying to write a shot script for my character. I’m following the tutorial on Pixelnest on how to do this, on the following section http://pixelnest.io/tutorials/2d-game-unity/shooting-1/

All my code is in JavaScript, and the tutorial is written in c# and there is one part that i just can’t get right. It’s in the last part of the WeaponScript on Pixelnest. It looks like this:

  /// <summary>
  /// Is the weapon ready to create a new projectile?
  /// </summary>
  public bool CanAttack
  {
    get
    {
      return shootCooldown <= 0f;
    }
  }
}

How would that part look like in JavaScript? Not sure on how to use “get”. Would very much appreciate if someone could help me with this. My full JavaScript version of WeaponScript looks like this (without the last part which i need help with):

#pragma strict

var projectile : Transform;
var canAttack : boolean;
var shootingRate : float;
var shootCooldown : float;

function Start () {
	shootCooldown = 0f;
}

function Update () {
	if (shootCooldown > 0) {
		shootCooldown -= Time.deltaTime;
	}
}

function Attack (isEnemy : boolean) {
	if (canAttack) {
		 shootCooldown = shootingRate;
		 var shotTransform : Transform;
		 shotTransform = Instantiate(projectile);
		 
		 // Assign position
		 shotTransform.position = transform.position;
		 
		 // The is enemy property
		 var shot : ShotScript = shotTransform.gameObject.GetComponent(ShotScript);
		 
		 if (shot != null) {
		 	shot.isEnemyShot = isEnemy;
		 }
	}
}

function get CanAttack { return shootCooldown <= 0 }

1 Answer

1

function get CanAttack () {
return shootCooldown <= 0f;
}

However, you should also not declare the canAttack variable, and use if(CanAttack) inside the Attack function.

You're missing the "get" keyword for actually turn the method into a property. If you declare it as "normal" method you have to use the calling brackets () when using it. Other than that you're right, remove "canAttack" and replace it with this property / method call

Thanks Bunny83, I corrected it!