Player cannot double jump - c#

I am following a tutorial on YouTube and everything is working fine until now, except I can only have one jump with this code, any advice ?
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class Player : MonoBehaviour {
public float power = 500;
public int jumpHeight = 1000;
public bool isFalling = false;
public int Score;
public Text SCORE;
public GameObject YOUDIED;
private int health = 3;
public GameObject health1;
public GameObject health2;
public GameObject health3;
public int Highscore;
private bool canDoubleJump;
private bool jumpOne;
private bool jumpTwo;
// Use this for initialization
void Start () {
YOUDIED.SetActive(false);
Highscore = PlayerPrefs.GetInt ("Highscore", 0);
jumpOne = false;
jumpTwo = false;
canDoubleJump = false;
}
void Update() {
if(Input.GetMouseButtonDown(0) && health == 0) {
Time.timeScale = 1f;
health = 3;
Application.LoadLevel(0);
}
if (health == 3) {
health1.SetActive (true);
health2.SetActive (true);
health3.SetActive (true);
}
if (health == 2) {
health1.SetActive (true);
health2.SetActive (true);
health3.SetActive (false);
}
if (health == 1) {
health1.SetActive (true);
health2.SetActive (false);
health3.SetActive (false);
}
if (health == 0) {
health1.SetActive (false);
health2.SetActive (false);
health3.SetActive (false);
}
if (health <= 0) {
YOUDIED.SetActive (true);
Time.timeScale = 0.0f;
}
SCORE.text = "Score " + Score;
transform.Translate(Vector2.right * power * Time.deltaTime);
if (Input.GetKeyDown(KeyCode.Space) && isFalling == false) {
jumpOne = true;
canDoubleJump = true;
isFalling = true;
}
if (Input.GetKeyDown(KeyCode.Space) && isFalling == true && canDoubleJump == true) {
jumpTwo = true;
canDoubleJump = false;
}
}
void FixedUpdate() {
if (jumpOne == true) {
GetComponent<Rigidbody2D>().AddForce(Vector2.up * jumpHeight);
jumpOne = false;
}
if (jumpTwo == true) {
GetComponent<Rigidbody2D>().AddForce(Vector2.up * jumpHeight);
jumpTwo = false;
}
}
void OnCollisionStay2D(Collision2D coll) {
if (coll.gameObject.tag == "Ground") {
isFalling = false;
canDoubleJump = false;
}
}
public void ScorePlus(int NewScore) {
Score += NewScore;
if(Score >= Highscore) {
Highscore = Score;
PlayerPrefs.SetInt ("Highscore", Highscore);
}
}
void OnTriggerEnter2D(Collider2D coll) {
if (coll.gameObject.tag == "Death") {
health -= 1;
}
}
}

canDoubleJump should be set to true here
void OnCollisionStay2D(Collision2D coll) {
if (coll.gameObject.tag == "Ground") {
isFalling = false;
canDoubleJump = false;
}
also in the first jump you need to set isFalling to true
if (jumpOne == true) {
GetComponent<Rigidbody2D>().AddForce(Vector2.up * jumpHeight);
jumpOne = false;
isFalling = true;
}
That should do the trick

Solved,
I put an else if statement instead of only an if
if (Input.GetKeyDown(KeyCode.Space) && isFalling == false) {
jumpOne = true;
canDoubleJump = true;
isFalling = true;
}else if (Input.GetKeyDown(KeyCode.Space) && isFalling == true && canDoubleJump == true) {
jumpTwo = true;
canDoubleJump = false;
}

Related

transfer damage based on the selected object

There are three scripts
1)Checks the mouse click on the object (unit), if it is a unit, then the backlight is turned on, this object is recorded in the target mob s variable. (everything is cool here, I even passed the targetmobs variable to the 2 script)
if the space key is pressed, then we must damage the selected target (based on targetmobs)(not working)
here are the characteristics of the unit (in particular health)
The problem is in accessing the variable based on the selected object
I attach the code
1)
public class Select : MonoBehaviour
{
public bool IsActive ;
public Camera selectCamera;
public GameObject[] mobs;
public GameObject targetmobs;
private RaycastHit hit;
bool selecting = false;
private float selectTimer = 0f;
void Awake()
{
mobs = GameObject.FindGameObjectsWithTag("Skelet");
}
void Start()
{
}
void Update()
{
Debug.Log(IsActive);
if (Input.GetMouseButtonDown(0))
{
CheckIfUnderMouse();
}
}
public void CheckIfUnderMouse()
{
Ray ray = selectCamera.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit, 100f))
{
if (hit.collider.gameObject.tag == "Skelet")
{
targetmobs = hit.collider.gameObject;
targetmobs.GetComponentInChildren<SelectableCharacter>().TurnOnSelector();
testdamagetounits.target = targetmobs;
Debug.Log("нажал и выбрал");
IsActive = true;
}
else
{
IsActive = false;
if(targetmobs != null)
{
targetmobs.GetComponentInChildren<SelectableCharacter>().TurnOffSelector();
targetmobs = null;
testdamagetounits.target = null;
}
Debug.Log("нажал в пустоту");
}
}
}
}
public class testdamagetounits : MonoBehaviour
{
int randomNumber;
int lastNumber;
int meleeDamage = 5;
int takedamage;
public static GameObject target;
void Start()
{
target = null;
randomNumber = Random.Range(0, 5);
}
void Update()
{
Randomize();
if (Input.GetKeyDown(KeyCode.Space))
{
tuTarget();
}
}
void Randomize()
{
randomNumber = Random.Range(0, 5);
if (randomNumber == lastNumber)
{
randomNumber = Random.Range(0, 5);
}
lastNumber = randomNumber;
}
void tuTarget()
{
if(target != null)
{
}
}
}
public class Target : MonoBehaviour
{
int randomNumber;
int lastNumber;
int damage;
public TextMeshProUGUI TextHealth;
public TextMeshProUGUI TextDamage;
public TargetHealthBar healthBar;
[Header("Характеристики")]
public int maxHealth = 122;
public int currentHealth;
void Start()
{
currentHealth = maxHealth;
healthBar.SetMaxHealth(maxHealth);
SelectHealth.currentHealth = currentHealth;
SelectHealth.maxHealth = maxHealth;
TextHealth.text = currentHealth.ToString()+ "/"+maxHealth.ToString();
}
void Update()
{
TakeDamage();
}
void TakeDamage()
{
if(currentHealth <=0 )
{
}
else
{
currentHealth -= damage;
TextDamage.text = "-" + damage.ToString();
}
healthBar.SetHealth(currentHealth);
TextHealth.text = currentHealth.ToString()+ "/"+maxHealth.ToString();
}
}
пробовал разные обращения через GetComponentInChildren().
но увы я новичок в программировании

sending an RPC with class instance give an error - unity Netcode

I'm using NetCode for GameObject 1.0.0 pre.5 in unity
and I keep getting the following error when I'm trying to send a ServerRPC
Assets\scrips\Weapons\Grenades.cs(72,13): error - Don't know how to serialize PlayerMessenger - implement INetworkSerializable or add an extension method for FastBufferWriter.WriteValueSafe to define serialization.
the method that give the error is Grenades.SetHealthDownServerRpc()
how take's an PlayerMassenger class instace
here's the my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Unity.Netcode;
namespace BeanBoxers.Weapons
{
[System.Serializable]
[implement : INetworkSerializable]
public class Grenades : NetworkBehaviour
{
public string PlayerTag;
public GameObject Particals;
public double Timer = 10;
public bool IsThouned = false;
public bool? Team {get; private set;} = null;
public float HitRadius = 5;
public float Demage = 120;
public float effectTime = .15f;
void Start()
{
Particals.SetActive(false);
if(!IsServer) {return;}
GetComponent<NetworkObject>().Spawn();
}
// Update is called once per frame
void Update()
{
if (!IsThouned) {return; }
else
{
Timer -= Time.deltaTime;
}
if (Timer <= 0)
{
explod();
}
}
public void explod()
{
Particals.SetActive(true);
IsThouned = false;
Collider[] hitColliders = Physics.OverlapSphere(transform.position, HitRadius);
foreach (var hitCollider in hitColliders)
{
if (!IsOwner) {break;}
if (hitCollider.tag == PlayerTag)
{
BeanBoxers.Player.PlayerMessenger Player = hitCollider.gameObject.GetComponent<BeanBoxers.Player.PlayerMessenger>();
if (Player.Team != Team || Team == null)
{
Vector3 HitDistanceVec3 = hitCollider.gameObject.transform.position - transform.position;
float Distance = Mathf.Abs(Mathf.Sqrt(HitDistanceVec3.x * HitDistanceVec3.x + HitDistanceVec3.y * HitDistanceVec3.y + HitDistanceVec3.z * HitDistanceVec3.z));
SetHealthDownServerRpc(Player ,Mathf.Abs(Mathf.Sin(90 / Distance)) * Demage);
}
}
}
GetComponent<MeshRenderer>().enabled = false;
Destroy(transform.gameObject, effectTime);
}
public void setTeam(bool? team)
{
Team = team;
}
[ServerRpc]
private void SetHealthDownServerRpc(BeanBoxers.Player.PlayerMessenger player, float Demage)
{
player.SetHealth(player.GetHealth() - Demage);
}
}
}
PlayerMassenger:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Unity.Netcode;
using TMPro;
namespace BeanBoxers.Player
{
[System.Serializable]
public class PlayerMessenger : NetworkBehaviour
{
protected static BeanBoxers.Guns.GunsTM GunsTaskManager = new BeanBoxers.Guns.GunsTM();//Managed the guns
//you can get from him a gun like so: GunsTaskManager.GetGun(<Gun name>);
public LayerMask groundMask;//a ground mask
public dynamic Gun{get; private set;}// store the gun from the GunsTM to a variable
public GameObject groundCheck{get; private set;}// store the GameObject that checks if the player touching
public CharacterController controller{get; private set;}// control the player
public GameObject GrenadePath{get; private set;}//store the force for the grande to fly to
private int MaxHealth = 100;//max health
public NetworkVariable<float> Health{get; private set;} = new NetworkVariable<float>(100);//my health
public float HealthRegnertion{get; private set;} = 3;// how fast the player does regnertion
public float gravity = -10.0f;//gravity
public float speed{get; private set;} = 100;//current speed
public float Ospeed{get; private set;}// oriaginal speed
private float groundDistnce = 0.4f;//the radus of the spire that chack if the payer touching th ground
private Vector3 velocity = new Vector3(0, 0, 0);//the player velocity
public float JumpVelocity{get; private set;} = 10f;// jump velocity
private bool isGrounded;// store if the player is grouded or not
public bool isSlideing{get; private set;} = false;//store if the player is slideing or not
private Vector3 slideScale = new Vector3(1.3f, 0.5f, 1.3f);//player scale
public float MaxSlideTime{get; private set;} = 10;// max slideing time
public float SlideingTime{get; private set;} = 0;//current slideing time
public bool isDead{get; private set;} = false;//is the player dead
private float RespawnTime = 5f;//how mach time is take the player to do a respawn
public bool? Team{get; private set;} = null;//true; red team, false; blue team, null; free for all
private string GunName = "PickerKicker";// my current gun name
public bool ShootTriger{get; private set;} = false;// am I polling the triger
public int GrandesLeft{get; private set;} = 3;
public int MaxNumberOfHoldedGrenades{get; private set;} = 3;
public bool IsHoldingGrenade{get; private set;} = false;
public float GrandeHoldTimer{get; private set;} = 0;
public float MaxHoldGrandeTime{get; private set;} = 5;
public int SmookeGrandesLeft{get; private set;} = 3;
public int MaxNumberOfHoldSmookeGrenades{get; private set;} = 3;
public bool IsHoldingSmookeGrenade{get; private set;} = false;
public float SmookeGrandeHoldTimer{get; private set;} = 0;
public float MaxHoldSmookeGrandeTime{get; private set;} = 5;
public int MortarLeft{get; private set;} = 3;
public int MaxNumberOfHoldedMortor{get; private set;} = 6;
public RayCheck Ray{get; private set;}// a RayCheck object
private GameObject UI;
private BeanBoxers.UI.Player.FaceTheCamera UIclass;
public double timer{get; private set;} = 0;// a timer
public NetworkVariable<bool> TryVariable = new NetworkVariable<bool>(false);
void Start()
{
groundCheck = transform.GetChild(0).gameObject;
Ospeed = speed;
controller = GetComponent<CharacterController>();
groundCheck.transform.parent = this.transform;
groundCheck.transform.localPosition = new Vector3(0, -1f, 0);
Ray = this.GetComponent<RayCheck>();
this.SetGunName(GunName);
EasterEggs();
groundMask = LayerMask.GetMask("Ground");
this.transform.position = new Vector3(0f, 10f, 0f);
if (IsOwner)
{
SetName(GameObject.Find("Menu").GetComponent<BeanBoxers.Multiplayer.MainMenu.MainMenu>().Name);
}
}
void Update()
{
//update UI
UIclass.update(this.transform.position, Health.Value, MaxHealth, name);
if (!isDead)
{
print(TryVariable);
//update
slideUpdate();
velocity.y += gravity * Time.deltaTime;
Vector3 move = new Vector3(velocity.x * speed, velocity.y, velocity.x * speed);
controller.Move(move * Time.deltaTime);
isGrounded = Physics.CheckSphere(groundCheck.transform.position, groundDistnce, groundMask);
if (isGrounded && velocity.y <= 0)
{
velocity.y = -2f;
}
//update the gun
Gun.Update();
//update the grenade
if (IsHoldingGrenade)
{
if (GrandeHoldTimer > MaxHoldGrandeTime)
{
GrandeHoldTimer = MaxHoldGrandeTime;
}
else
{
GrandeHoldTimer += Time.deltaTime;
}
}
//update the smooke grenade
if (IsHoldingSmookeGrenade)
{
if (SmookeGrandeHoldTimer > MaxHoldSmookeGrandeTime)
{
SmookeGrandeHoldTimer = MaxHoldSmookeGrandeTime;
}
else
{
SmookeGrandeHoldTimer += Time.deltaTime;
}
}
//check the ray cast
if (ShootTriger)
{
if (Gun.Shoot())
{
PlayerMessenger output = Ray.CheckWhatRayHit();
if (output != null)
{
output.SetHealth(output.GetHealth() - Gun.TakeDemage(this.transform.position, output.transform.position));
}
}
}
if (Health.Value <= 0)
{
isDead = true;
// ServerRpc();
if (!IsOwner) {return;}
DiedServerRpc();
//make Sure the player position update when he die
Disable();
Invoke("Spawn", 5);
}
else if (Health.Value < MaxHealth)
{
Health.Value += HealthRegnertion * Time.deltaTime;
}
}
}
public void Spawn()
{
Enable();
isDead = false;
timer = 0;
Health.Value = MaxHealth;
GrandesLeft = MaxNumberOfHoldedGrenades;
SmookeGrandesLeft = MaxNumberOfHoldSmookeGrenades;
MortarLeft = MaxNumberOfHoldedMortor;
}
public void SetGunName(string gunName)
{
if (!IsServer) {return;}
this.GunName = gunName;
Gun = GunsTaskManager.GetGun(GunName);
Gun.setParent(Ray.RayStarter);
}
public string GetGunName()
{
return GunName;
}
public void SetName(string name)
{
if (!IsServer) {return;}
this.name = name;
EasterEggs();
}
public string GetName(string name)
{
return name;
}
public void SetHealth(float Health)
{
if (!IsServer) {return;}
this.Health.Value = Health;
if (Health > 0) {return;}
DiedServerRpc();
}
public float GetHealth()
{
return Health.Value;
}
[ServerRpc]
private void DiedServerRpc()
{
DiedClientRpc();
}
[ClientRpc]
private void DiedClientRpc()
{
if (IsOwner) {return;}
//make Sure the player position update when he die
isDead = true;
Disable();
Invoke("Spawn", 5);
}
public void SetSpeed(float NewSpeed)
{
if (!IsServer) {return;}
speed = NewSpeed;
}
public void SetMaxHealth(int Max_Health)
{
if (!IsServer) {return;}
MaxHealth = Max_Health;
}
public void changeTeam(bool? team)
{
if (!IsServer) {return;}
Team = team;
}
private void Disable()
{
transform.gameObject.SetActive(false);
}
private void Enable()
{
transform.gameObject.SetActive(true);
}
private void EasterEggs()
{
if (name == "Eti Ben Simon") {MaxHealth *= 2; Health.Value = MaxHealth;}
}
public void shootTriger(bool val)
{
ShootTriger = val;
shootTrigerServerRpc(val);
}
[ServerRpc]
private void shootTrigerServerRpc(bool val)
{
ShootTriger = val;
shootTrigerClientRpc(val);
}
[ClientRpc]
private void shootTrigerClientRpc(bool val)
{
if(IsOwner) {return;}
ShootTriger = val;
}
public void Jump()
{
if(!IsOwner) {return;}
JumpServerRpc();
if (isGrounded)
{
velocity.y = JumpVelocity;
unslide();
}
}
[ServerRpc]
private void JumpServerRpc()
{
JumpClientRpc();
}
[ClientRpc]
private void JumpClientRpc()
{
if (isGrounded)
{
velocity.y = JumpVelocity;
unslide();
}
}
public void slide()
{
if(!IsOwner) {return;}
slideServerRpc();
if (isGrounded)
{
speed = Ospeed * 2;
isSlideing = true;
transform.localScale = slideScale;
}
}
[ServerRpc]
private void slideServerRpc()
{
slideClientRpc();
speed = Ospeed;
isSlideing = false;
Vector3 newScale = new Vector3(1f, 1f, 1f);
transform.localScale = newScale;
}
[ClientRpc]
private void slideClientRpc()
{
if(IsOwner) {return;}
if (isGrounded)
{
speed = Ospeed * 2;
isSlideing = true;
transform.localScale = slideScale;
}
}
public void unslide()
{
if(!IsOwner) {return;}
unslideServerRpc();
speed = Ospeed;
isSlideing = false;
Vector3 newScale = new Vector3(1f, 1f, 1f);
transform.localScale = newScale;
}
[ServerRpc]
private void unslideServerRpc()
{
unslideClientRpc();
speed = Ospeed;
isSlideing = false;
Vector3 newScale = new Vector3(1f, 1f, 1f);
transform.localScale = newScale;
}
[ClientRpc]
private void unslideClientRpc()
{
if(IsOwner) {return;}
speed = Ospeed;
isSlideing = false;
Vector3 newScale = new Vector3(1f, 1f, 1f);
transform.localScale = newScale;
}
public void slideUpdate()
{
if (isSlideing)
{
SlideingTime += Time.deltaTime;
}
else
{
SlideingTime -= Time.deltaTime / 2;
if (SlideingTime < 0)
{
SlideingTime = 0;
}
}
if (SlideingTime >= MaxSlideTime)
{
unslide();
}
}
public void ThrowGrenade()
{
if (!IsOwner) {return;}
if (GrandesLeft > 0)
{
Debug.Log("Grenade.Throw");
GameObject Grande = Instantiate(Resources.Load("3Dmodels/Weapons/Grenade")) as GameObject;
Grande.transform.position = GrenadePath.transform.position;
BeanBoxers.Weapons.Grenades G = Grande.GetComponent<BeanBoxers.Weapons.Grenades>();
Rigidbody GrenadeRigidbody = Grande.GetComponent<Rigidbody>();
G.setTeam(Team);
G.IsThouned = true;
GrenadeRigidbody.AddForce((GrenadePath.transform.position - transform.position) * GrandeHoldTimer * 170);
GrenadeRigidbody.AddTorque(new Vector3(UnityEngine.Random.Range(-180, 180), UnityEngine.Random.Range(-180, 180), UnityEngine.Random.Range(-180, 180)));
GrandeHoldTimer = 0;
IsHoldingGrenade = false;
GrandesLeft -= 1;
}
}
public void isHoldingGrenade(bool val)
{
if (!IsOwner) {return;}
IsHoldingGrenade = val;
}
[ServerRpc]
private void IsHoldingGrenadeServerRpc(bool val)
{
IsHoldingGrenade = val;
IsHoldingGrenadeClientRpc(val);
}
[ClientRpc]
private void IsHoldingGrenadeClientRpc(bool val)
{
if (IsOwner) {return;}
IsHoldingGrenade = val;
}
public void ThrowSmookeGrenade()
{
if (!IsOwner) {return;}
if (SmookeGrandesLeft < 0) {return;}
Debug.Log("SmookeGrenade.Throw");
GameObject Grande = Instantiate(Resources.Load("3Dmodels/Weapons/SmookeGrenade")) as GameObject;
Grande.transform.position = GrenadePath.transform.position;
BeanBoxers.Weapons.Grenades G = Grande.GetComponent<BeanBoxers.Weapons.Grenades>();
Rigidbody GrenadeRigidbody = Grande.GetComponent<Rigidbody>();
G.setTeam(Team);
G.IsThouned = true;
GrenadeRigidbody.AddForce((GrenadePath.transform.position - transform.position) * SmookeGrandeHoldTimer * 170);
GrenadeRigidbody.AddTorque(new Vector3(UnityEngine.Random.Range(-180, 180), UnityEngine.Random.Range(-180, 180), UnityEngine.Random.Range(-180, 180)));
SmookeGrandeHoldTimer = 0;
IsHoldingSmookeGrenade = false;
SmookeGrandesLeft -= 1;
}
public void isHoldingSmookeGrenade(bool val)
{
if (!IsOwner) {return;}
IsHoldingSmookeGrenade = val;
}
[ServerRpc]
private void IsHoldingSmookeGrenadeServerRpc(bool val)
{
IsHoldingSmookeGrenade = val;
IsHoldingSmookeGrenadeClientRpc(val);
}
[ClientRpc]
private void IsHoldingSmookeGrenadeClientRpc(bool val)
{
if (IsOwner) {return;}
IsHoldingSmookeGrenade = val;
}
public void PutMortar()
{
if (!IsOwner) {return;}
if (MortarLeft < 0) {return;}
GameObject mortor = Instantiate(Resources.Load("3Dmodels/Weapons/Mortor")) as
GameObject;
mortor.transform.position = GrenadePath.transform.position;
mortor.transform.Rotate(46f, GrenadePath.transform.eulerAngles.y + 180, -90f);
MortarLeft -= 1;
}
}
}
my scripts aren't the best, I know but anybody have any idea why I get the error? it will very help me
I guess you could first off try to do what the error says: "Implement INetworkSerializable". To Implement that Interface you would write: ...Grenades : Networkbehavior, INetworkSerializable. I don't know if [implement: ...] works so that is just a guess based off of your error.

How can I lower the opacity of a game object in an array when a specific event occurs?

For example, in my game, I want these small player icons to turn transparent when the player dies. I already have a function called PlayerDead, but when I put the game object in the function, I can't access the sprite renderer. I would preferably like to not attach my main script to the icon, but I really have no clue how to do it. For reference, _checkForGameOver is a counter to see how many times the player/enemy has died. When the player dies, a question mark in place of where the icon is destroyed, and the icon is instantiated in that spot. Here is a portion of the code from the main script:
public GameObject[] playerPrefab;
public GameObject[] enemyPrefab;
public GameObject[] icon;
public GameObject[] questionMarks;
public Transform playerSpawn;
public Transform enemySpawn;
public Transform topSpawn;
public Transform middleSpawn;
public Transform bottomSpawn;
public Transform topSpawnEnemy;
public Transform middleSpawnEnemy;
public Transform bottomSpawnEnemy;
Unit playerUnit;
Unit enemyUnit;
int randomIntPlayer;
int randomIntEnemy;
public bool playerPassDamage;
public BattleHUD playerHUD;
public BattleHUD enemyHUD;
public BattleState state;
public Button attackButton;
public Button passButtonDamage;
public Button healButton;
public Button passButtonResistance;
public GameObject playAgain;
public GameObject circleAttack;
public GameObject squareAttack;
public IconColor iconColor;
public Shake shake;
private int _checkForGameOverPlayer { get; set; } = 0;
private int _checkForGameOverEnemy { get; set; } = 0;
void Start()
{
shake = GameObject.FindGameObjectWithTag("ScreenShake").GetComponent<Shake>();
state = BattleState.START;
StartCoroutine(SetupBattle());
}
IEnumerator SetupBattle()
{
randomIntPlayer = Random.Range(0, playerPrefab.Length);
GameObject playerGO = Instantiate(playerPrefab[randomIntPlayer], playerSpawn);
playerUnit = playerGO.GetComponent<Unit>();
if(randomIntPlayer == 0)
{
Instantiate(icon[0], topSpawn);
}
else if (randomIntPlayer == 1)
{
Instantiate(icon[1], topSpawn);
}
else if (randomIntPlayer == 2)
{
Instantiate(icon[2], topSpawn);
}
else if (randomIntPlayer == 3)
{
Instantiate(icon[3], topSpawn);
}
randomIntEnemy = Random.Range(0, enemyPrefab.Length);
GameObject enemyGO = Instantiate(enemyPrefab[randomIntEnemy], enemySpawn);
enemyUnit = enemyGO.GetComponent<Unit>();
if (randomIntEnemy == 0)
{
Instantiate(icon[0], topSpawnEnemy);
}
else if (randomIntEnemy == 1)
{
Instantiate(icon[1], topSpawnEnemy);
}
else if (randomIntEnemy == 2)
{
Instantiate(icon[2], topSpawnEnemy);
}
else if (randomIntEnemy == 3)
{
Instantiate(icon[3], topSpawnEnemy);
}
playerUnit.GetComponentInChildren<SpriteRenderer>().enabled = true;
enemyUnit.GetComponentInChildren<SpriteRenderer>().enabled = true;
playerHUD.SetHUD(playerUnit);
enemyHUD.SetHUD(enemyUnit);
playerPassDamage = false;
didPlayerHeal = false;
if (playerUnit.speed > enemyUnit.speed)
{
state = BattleState.PLAYERTURN;
PlayerTurn();
}
else if (enemyUnit.speed > playerUnit.speed)
{
passButtonDamage.interactable = false;
attackButton.interactable = false;
healButton.interactable = false;
passButtonResistance.interactable = false;
state = BattleState.ENEMYTURN;
yield return new WaitForSeconds(1.2f);
StartCoroutine(EnemyTurn());
}
}
public IEnumerator EnemyDead()
{
_checkForGameOverEnemy++;
if (_checkForGameOverEnemy == 1)
{
if (randomIntEnemy == 0)
{
}
else if (randomIntEnemy == 1)
{
}
else if (randomIntEnemy == 2)
{
}
else if (randomIntEnemy == 3)
{
}
}
if (_checkForGameOverEnemy == 3)
{
state = BattleState.WON;
EndBattle();
}
yield return new WaitForSeconds(.25f);
randomIntEnemy = Random.Range(0, enemyPrefab.Length);
GameObject enemyGO = Instantiate(enemyPrefab[randomIntEnemy], enemySpawn);
enemyUnit = enemyGO.GetComponent<Unit>();
if (_checkForGameOverEnemy == 1)
{
Destroy(questionMarks[2]);
if (randomIntEnemy == 0)
{
Instantiate(icon[0], middleSpawnEnemy);
}
else if (randomIntEnemy == 1)
{
Instantiate(icon[1], middleSpawnEnemy);
}
else if (randomIntEnemy == 2)
{
Instantiate(icon[2], middleSpawnEnemy);
}
else if (randomIntEnemy == 3)
{
Instantiate(icon[3], middleSpawnEnemy);
}
}
if (_checkForGameOverEnemy == 2)
{
Destroy(questionMarks[3]);
if (randomIntEnemy == 0)
{
Instantiate(icon[0], bottomSpawnEnemy);
}
else if (randomIntEnemy == 1)
{
Instantiate(icon[1], bottomSpawnEnemy);
}
else if (randomIntEnemy == 2)
{
Instantiate(icon[2], bottomSpawnEnemy);
}
else if (randomIntEnemy == 3)
{
Instantiate(icon[3], bottomSpawnEnemy);
}
}
enemyHUD.SetHUD(enemyUnit);
if (playerUnit.speed > enemyUnit.speed)
{
state = BattleState.PLAYERTURN;
PlayerTurn();
}
else if (enemyUnit.speed > playerUnit.speed)
{
passButtonDamage.interactable = false;
attackButton.interactable = false;
healButton.interactable = false;
passButtonResistance.interactable = false;
yield return new WaitForSeconds(1f);
state = BattleState.ENEMYTURN;
StartCoroutine(EnemyTurn());
}
}
IEnumerator PlayerDead()
{
_checkForGameOverPlayer++;
if (_checkForGameOverEnemy == 1)
{
if (randomIntPlayer == 0)
{
}
else if (randomIntPlayer == 1)
{
}
else if (randomIntPlayer == 2)
{
}
else if (randomIntPlayer == 3)
{
}
}
if (_checkForGameOverPlayer == 3)
{
state = BattleState.LOST;
EndBattle();
}
yield return new WaitForSeconds(.25f);
randomIntPlayer = Random.Range(0, playerPrefab.Length);
GameObject playerGO = Instantiate(playerPrefab[randomIntPlayer], playerSpawn);
playerUnit = playerGO.GetComponent<Unit>();
if (_checkForGameOverPlayer == 1)
{
Destroy(questionMarks[0]);
if (randomIntPlayer == 0)
{
Instantiate(icon[0], middleSpawn);
}
else if (randomIntPlayer == 1)
{
Instantiate(icon[1], middleSpawn);
}
else if (randomIntPlayer == 2)
{
Instantiate(icon[2], middleSpawn);
}
else if (randomIntPlayer == 3)
{
Instantiate(icon[3], middleSpawn);
}
}
if (_checkForGameOverPlayer == 2)
{
Destroy(questionMarks[1]);
if (randomIntPlayer == 0)
{
Instantiate(icon[0], bottomSpawn);
}
else if (randomIntPlayer == 1)
{
Instantiate(icon[1], bottomSpawn);
}
else if (randomIntPlayer == 2)
{
Instantiate(icon[2], bottomSpawn);
}
else if (randomIntPlayer == 3)
{
Instantiate(icon[3], bottomSpawn);
}
}
playerHUD.SetHUD(playerUnit);
if (playerUnit.speed > enemyUnit.speed)
{
state = BattleState.PLAYERTURN;
PlayerTurn();
}
else if (enemyUnit.speed > playerUnit.speed)
{
passButtonDamage.interactable = false;
attackButton.interactable = false;
healButton.interactable = false;
passButtonResistance.interactable = false;
yield return new WaitForSeconds(1f);
state = BattleState.ENEMYTURN;
StartCoroutine(EnemyTurn());
}
}
If you're using SpriteRenderer to render the icon, then you can use GetComponent<SpriteRenderer>().color to access it's color, and your opacity value can be accessed via Color.a, which means alpha. 0 means it's transparent, 1 means it's full-visible. Here's my suggestion:
foreach (var g in icon)
{
if (g == null) continue;
var sprite = g.GetComponent<SpriteRenderer>();
var color = sprite.color;
sprite.color = new Color(color.r, color.g, color.b, 0)
}
Be careful that since it contains GetComponent(), it's not recommended to do like so in Update() function. Only do this when the event has "Actually" occured.

how to make PlayerController Script use Touch Input

How do I make my PlayerController Script get touch input to make the player move in unity5? I tried changing the Input.GetKeyDown to GetMouseDown and GetTouch, but nothing happens when ever I click on the buttons, please help...thanks in advance.
using UnityEngine;
using System.Collections;
public class PlayerController : MonoBehaviour {
private static PlayerController instance;
public static PlayerController Instance
{
get
{
if(instance == null)
{
instance = GameObject.FindObjectOfType<PlayerController>();
}
return instance;
}
}
private Animator myAnimator;
[SerializeField]
private Transform bulletPosition;
[SerializeField]
private float movementSpeed;
private bool facingRight;
[SerializeField]
private Transform[] groundPoints;
[SerializeField]
private float groundRadius;
[SerializeField]
private LayerMask whatIsGround;
[SerializeField]
public bool airControl;
[SerializeField]
private float jumpForce;
[SerializeField]
private GameObject bulletPrefab;
public Rigidbody2D MyRigidbody{ get; set;}
public bool Attack{ get; set;}
public bool Jump{ get; set;}
public bool OnGround{ get; set;}
// Use this for initialization
void Start ()
{
facingRight = true;
MyRigidbody = GetComponent<Rigidbody2D>();
myAnimator = GetComponent<Animator>();
}
// Update is called once per frame
void Update()
{
HandleInput();
}
void FixedUpdate()
{
float horizontal = Input.GetAxis("Horizontal");
Debug.Log(horizontal);
OnGround = IsGrounded();
HandleMovement(horizontal);
Flip(horizontal);
HandleLayers();
}
private void HandleMovement(float horizontal)
{
if (MyRigidbody.velocity.y < 0)
{
myAnimator.SetBool("land", true);
}
if (!Attack && (OnGround || airControl))
{
MyRigidbody.velocity = new Vector2(horizontal * movementSpeed, MyRigidbody.velocity.y);
}
if (Jump && MyRigidbody.velocity.y == 0)
{
MyRigidbody.AddForce(new Vector2(0, jumpForce));
}
myAnimator.SetFloat ("speed", Mathf.Abs (horizontal));
}
private void HandleInput()
{
if(Input.GetKeyDown(KeyCode.Space))
{
myAnimator.SetTrigger("jump");
}
if(Input.GetKeyDown(KeyCode.C))
{
myAnimator.SetTrigger("attack");
}
}
private void Flip(float horizontal)
{
if(horizontal > 0 && !facingRight || horizontal < 0 && facingRight)
{
facingRight = !facingRight;
Vector3 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
}
}
private bool IsGrounded()
{
if(MyRigidbody.velocity.y <= 0)
{
foreach(Transform point in groundPoints)
{
Collider2D[] colliders = Physics2D.OverlapCircleAll(point.position, groundRadius, whatIsGround);
for(int i = 0; i <colliders.Length; i++)
{
if(colliders[i].gameObject != gameObject)
{
return true;
}
}
}
}
return false;
}
private void HandleLayers()
{
if(!OnGround)
{
myAnimator.SetLayerWeight(1, 1);
}
else
{
myAnimator.SetLayerWeight(1, 0);
}
}
public void ShootBullet(int value)
{
if(!OnGround && value == 1 || OnGround && value == 0)
{
if (facingRight)
{
GameObject tmp = (GameObject)Instantiate(bulletPrefab, bulletPosition.position, Quaternion.Euler(new Vector3(0, 0, 0)));
tmp.GetComponent<Bullet>().Initialize(Vector2.right);
}
else
{
GameObject tmp = (GameObject)Instantiate(bulletPrefab, bulletPosition.position, Quaternion.Euler(new Vector3(0, 0, 180)));
tmp.GetComponent<Bullet>().Initialize(Vector2.left);
}
}
}
}

How to lose control in few seconds?

At the starting of GameState.Running, i want to stop input key in 3 seconds, after that, every time when my character take damage, i want to lose control in 1 second, could anyone show me how to do that?
public override void Update(GameTime gameTime, KeyboardState Current, KeyboardState Old)
{
float elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds;
if (TimeGetReady < 0)
{
LockKey = false;
}
else
{
LockKey = true;
TimeGetReady -= elapsed;
}
if (LockKey == false)
{
CurrentKeys = Current;
OldKeys = Old;
}
if (CurrentKeys.IsKeyDown(Keys.P))
{
if (!OldKeys.IsKeyDown(Keys.P))
if (IsPause == true)
IsPause = false;
else
IsPause = true;
}
if (IsPause == true)
{
return;
}
Update(elapsed);
if (CurrentKeys.IsKeyDown(Keys.Left))
{
KeyLeft = true;
if (HPF < 3)
HPF += 2;
PushHorizontal += 5;
Face = -1;
}
else
if (Old.IsKeyDown(Keys.Left))
{
KeyLeft = false;
}
if (CurrentKeys.IsKeyDown(Keys.Right))
{
KeyRight = true;
PushHorizontal += 5;
if (HPF < 3)
HPF += 2;
Face = 1;
}
else
if (Old.IsKeyDown(Keys.Right))
{
KeyRight = false;
}
if (KeyLeft == true || KeyRight == true)
{
KeyMove = true;
}
else
{
KeyMove = false;
}
if (KeyLeft == true && KeyRight == true)
{
KeyLeft = false;
KeyRight = false;
KeyMove = false;
}
if (CurrentKeys.IsKeyDown(Keys.X))
{
if (LockKeyX == false)
{
KeyJump = true;
LockKeyX = true;
PushVertical += 500;
}
if (VPF < 8)
VPF += 3;
}
else
if (Old.IsKeyDown(Keys.X))
{
KeyJump = false;
}
if (CurrentKeys.IsKeyUp(Keys.X))
{
if (Down == true)
{
LockKeyX = false;
}
}
if (CurrentKeys.IsKeyDown(Keys.Z))
{
if (LockKeyZ == false)
{
KeyDash = true;
KeyJump = false;
LockKeyZ = true;
PushHorizontal += 100;
}
if (KeyDash == true)
{
HPF = 1;
PushVertical += Gravity;
VPF = Gravity;
}
}
else
if (Old.IsKeyDown(Keys.Z))
{
KeyDash = false;
}
if (CurrentKeys.IsKeyUp(Keys.Z))
{
if (KeyMove == false && Down == true)
LockKeyZ = false;
}
if (CurrentKeys.IsKeyDown(Keys.C))
{
ChargeTime += elapsed;
if (LockKeyC == false)
{
LockKeyC = true;
TimeShot += 10f;
StayShot.ResetFrame();
}
}
else
if (Old.IsKeyDown(Keys.C))
{
if (ChargeTime > 0)
{
TimeShot += 0.4f;
ChargeTime = 0;
}
LockKeyC = false;
}
Update(elapsed);
UpdateInteraction();
if (TimeGetReady <= 0)
{
UpdateStatus(gameTime);
}
UpdateFrameStatus(elapsed);
LastStatus = RockmanStatus;
}
You need some InputManager that you update only when you need. Here is example of basic verstion of InputManager.
public override void Update(){
if(updateKeyboard) {InputManager.Update()}
}
new InputManager Class
public static class InputManager
{
public static void Update()
{
_previousKeyboardState = _currentKeyboardState;
_currentKeyboardState = Keyboard.GetState();
}
public static bool IsKeyDown(Keys key)
{
return _currentKeyboardState.IsKeyDown(key);
}
public static bool IsKeyUp(Keys key)
{
return _currentKeyboardState.IsKeyUp(key);
}
public static bool OnKeyDown(Keys key)
{
return _currentKeyboardState.IsKeyDown(key) && _previousKeyboardState.IsKeyUp(key);
}
public static bool OnKeyUp(Keys key)
{
return _currentKeyboardState.IsKeyUp(key) && _previousKeyboardState.IsKeyDown(key);
}
private static KeyboardState _currentKeyboardState;
private static KeyboardState _previousKeyboardState;
}

Categories

Resources