Player object automatically jumping when hitting start button - c#

I have a canvas that is initialized when I launch the game and inside it I have a menu with the play and quit button. The game is a endless runner and everything is working fine, but when I hit the Play button to actually start the game, the Player object automatically gives me one jump, after that, it's all normal, it's like when I hit Play button it hits the game and the player too at the same time. I need this working in a Android device.
Player.cs script
...
void Start () {
Highscore = PlayerPrefs.GetInt ("Highscore", 0);
jumpOne = false;
jumpTwo = false;
canDoubleJump = false;
}
void Update() {
for (int i = 0; i < Input.touchCount; i++){
if (Input.GetTouch(i).phase == TouchPhase.Began && isFalling == false) {
jumpOne = true;
canDoubleJump = true;
isFalling = true;
}else if (Input.GetTouch(i).phase == TouchPhase.Began && isFalling == true && canDoubleJump == true) {
jumpTwo = true;
canDoubleJump = false;
}
}
}
void FixedUpdate() {
transform.Translate(Vector2.right * power * Time.deltaTime);
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;
}
}
...
//(Play Button)
public void ClickedStart() {
MainMenu.SetActive(false);
Time.timeScale = 1.0f;
Playing = true;
}
Already tried and the problem still persists
(Input.GetMouseButtonDown(0))
(Input.GetKeyDown(KeyCode.Space)) Works fine and with no bugs, but I am not able to jump running in Android.

You are using TouchPhase.Began so the moment u hide your main menu the touch is still active and hence the player jumps , I suggest you use a co-routine with waitforseconds method before you can start making the player jump again .

Related

Unity C# Not taking in certain Input

I am creating a FPS game, my player has abilities and her ultimate is Jett's ultimate from Valorant (Her weapon switches to 5 knives that she can throw at enemies) I've managed to make the weapon switch to the knives but when I press the Mouse Left-Click nothing happens. I disabled the script that controls the gun so that the player does shoot bullets, have muzzle flash etc but whether its enabled or disabled the knives don't work. I added debug logs and they arent being called, I use the same button to shoot the gun as throwing the knife. I have also tested it without the 'readyToThrow' variable and 'totalThrows' variable.
Update Method:
void Update()
{
if (Time.time >= QabilityTimer && Input.GetKeyDown(KeyCode.Q))
{
Dash();
QabilityTimer = Time.time + Qcooldown;
}
if (Time.time >= EabilityTimer && Input.GetKeyDown(KeyCode.E))
{
SpeedBoost();
EabilityTimer = Time.time + Ecooldown;
}
if (meterButton.currentProgress == meterButton.maxProgress)
{
ultReady = true;
// Debug.Log("ult ready");
if (Input.GetKeyDown(KeyCode.X))
{
//disable the gun script whilst ult is active.
GameObject gun = GameObject.Find("Guns");
gun.GetComponent<Guns>().enabled = false;
weaponSelection.EunhaUltKnife();
EunhaUltimate();
}
}
if (ultActive)
{
ultTimer -= Time.deltaTime;
}
if (ultTimer <= 0)
{
ResetUltimate();
}
}
Ultimate Method:
public void EunhaUltimate()
{
ultActive = true;
if (Input.GetKeyDown(KeyCode.Mouse0) && readyToThrow && totalThrows > 0)
{
Debug.Log("working");
readyToThrow = false;
GameObject projectile = Instantiate(objectToThrow, attackPoint.position, cam.rotation);
Rigidbody projectileRB = projectile.GetComponent<Rigidbody>();
Vector3 forceToAdd = cam.transform.forward * throwForce + transform.up * throwUpwardForce;
projectileRB.AddForce(forceToAdd, ForceMode.Impulse);
totalThrows--;
Invoke(nameof(ReserThrow), throwCooldown);
}
}
Looks like you can only get into the EunhaUltimate() if you're holding down X:
if (meterButton.currentProgress == meterButton.maxProgress)
{
ultReady = true;
// Debug.Log("ult ready");
if (Input.GetKeyDown(KeyCode.X))
{
//disable the gun script whilst ult is active.
GameObject gun = GameObject.Find("Guns");
gun.GetComponent<Guns>().enabled = false;
weaponSelection.EunhaUltKnife();
EunhaUltimate();
}
}
Try moving the call to EunhaUltimate() outside of that IF statement. You'll need to have a trigger to show when you've pushed X to trigger the ultimate, but it looks like you're currently doing that inside EunhaUltimate(), with the ultActive = true; line.
Other than setting ultActive = true;, all your EunhaUltimate() seems to do is to check the keyboard press, so I'd recommend rewriting your first snippet as follows:
void Update()
{
if (Time.time >= QabilityTimer && Input.GetKeyDown(KeyCode.Q))
{
Dash();
QabilityTimer = Time.time + Qcooldown;
}
if (Time.time >= EabilityTimer && Input.GetKeyDown(KeyCode.E))
{
SpeedBoost();
EabilityTimer = Time.time + Ecooldown;
}
if (meterButton.currentProgress == meterButton.maxProgress)
{
ultReady = true;
// Debug.Log("ult ready");
if (Input.GetKeyDown(KeyCode.X))
{
//disable the gun script whilst ult is active.
GameObject gun = GameObject.Find("Guns");
gun.GetComponent<Guns>().enabled = false;
weaponSelection.EunhaUltKnife();
ultActive = true; // <--- This is a change
}
}
if (ultActive)
{
EunhaUltimate(); // <-- this is a change
ultTimer -= Time.deltaTime;
}
if (ultTimer <= 0)
{
ResetUltimate();
}
}
Try using Input.GetKey(KeyCode.Mouse0) or Input.GetKeyUp(KeyCode.Mouse0) instead Input.GetKeyDown(KeyCode.Mouse0).

Unity Gun Ammo not Decreasing Problem in Multiplayer (Maybe Related To my Multiplayer System: Photon)

I have a problem in which my ammo won't decrease when I shoot until I wait for a certain Amount of time. I'm currently using Photon as my Network System for my game and my gun code from Brackeys (https://www.youtube.com/watch?v=kAx5g9V5bcM&lc=UghlAulu5dH90HgCoAEC). This is maybe related to internet problems and delays but I'll show you the code I use:
void Update()
{
if(!photonView.IsMine) return;
if (!canShowAmmo)
{
ammoText.text = "Ammo: " + currentAmmo;
}
if (isStarted && (owner.openPanel || MultiplayerManager.main.roomManager.gameDone))
{
if (isScoped)
{
Scope();
}
return;
}
if (currentAmmo <= 0)
{
StartCoroutine(Reload());
return;
}
if(autoOrSemi == true){
if(Input.GetButton("Fire1") && Time.time >= nextTime){
nextTime = Time.time + 1f/fireRate;
Shoot();
}
}
if(autoOrSemi == false){
if(Input.GetButtonDown("Fire1") && Time.time >= nextTime){
nextTime = Time.time + 1f/fireRate;
Shoot();
}
}
if (Input.GetButtonDown("Fire2"))
{
Scope();
}
}
public void Shoot(){
MuzzleFlash.Play();
currentAmmo--;
AudioSource.PlayClipAtPoint(shotSound, transform.position);
RaycastHit hit;
if (Physics.Raycast(fpsCam.transform.position, fpsCam.transform.forward, out hit, range)){
Debug.Log(hit.transform.name);
IDamageable target = hit.collider.gameObject.GetComponent<IDamageable>();
if (target != null)
{
if (hit.collider != owner.GetComponent<Collider>())
{
target.TakeDamage(damage);
owner.score += (int) damage;
owner.ScoreUpdate();
}
}
if(hit.rigidbody != null){
hit.rigidbody.AddForce(-hit.normal * impactForce);
}
GameObject effect = Instantiate(impactEffect, hit.point, Quaternion.LookRotation(hit.normal));
Destroy(effect, 2f);
}
}
public IEnumerator Reload(){
isReloading = true;
Debug.Log("Reloading");
canShowAmmo = true;
ammoText.text = "Reloading...";
yield return new WaitForSeconds(reloadTime - .25f);
yield return new WaitForSeconds(.25f);
canShowAmmo = false;
currentAmmo = maxAmmo;
isReloading = false;
}
so if I was correct and it's caused by lag or I was wrong and didn't have any relation to the Network, please I need a solution. Thanks.
Sorry my bad, I may just found a solution: just add a new private bool and set it to true inside the if function derHugo presented below or above this comment and if bool is false then shooting is disabled then after reloading inside the enumerator after isReloading = false, make the bool to false
I think you issue are concurrent Coroutines!
you are doing
if (currentAmmo <= 0)
{
StartCoroutine(Reload());
return;
}
This will start a new routine every frame while the condition is met.
You rather want to do e.g.
if (!isReloading && currentAmmo <= 0)
{
StartCoroutine(Reload());
return;
}
if(isReloading) return;

Why aren't the animations working for this 2D unity character controller script

I have some code that makes a player move up, down, left, and right.
public class playerMovement : MonoBehaviour
{
public float moveSpeed = 5f;
public Rigidbody2D rb;
public Animator animator;
public SpriteRenderer sr;
Vector2 movement;
bool walking = false;
private void Update()
{
//Inputs
movement.x = Input.GetAxisRaw("Horizontal");
movement.y = Input.GetAxisRaw("Vertical");
if (Input.GetKey("left") || Input.GetKey("right") || Input.GetKey("up") || Input.GetKey("down")
{
walking = true;
}
else
{
walking = false;
}
Animate();
}
private void Animate()
{
if (Input.GetKey("down") && walking == false)
{
sr.flipX = false;
animator.Play("idle_front");
}
else if (Input.GetKey("down") && walking)
{
sr.flipX = false;
animator.Play("walk_front");
}
else if (Input.GetKey("up") && walking == false)
{
sr.flipX = false;
animator.Play("idle_back");
}
else if (Input.GetKey("down") && walking)
{
sr.flipX = false;
animator.Play("walk_back");
}
else if (Input.GetKey("left") && walking == false)
{
sr.flipX = false;
animator.Play("idle_side");
}
else if (Input.GetKey("down") && walking)
{
sr.flipX = false;
animator.Play("walk_side");
}
else if (Input.GetKey("right") && walking == false)
{
sr.flipX = true;
animator.Play("idle_side");
}
else if (Input.GetKey("right") && walking)
{
sr.flipX = true;
animator.Play("walk_side");
}
}
public void FixedUpdate()
{
//Movement
rb.MovePosition(rb.position + movement * moveSpeed * Time.fixedDeltaTime);
}
}
The movement is working perfectly fine, but the character just stays in it's idle state.
I have tried switching the get keys in Input.GetKey("left") || Input.GetKey("right") || Input.GetKey("up") || Input.GetKey("down") to Input.GetKeyDown() and Input.GetKeyUp(), but none of that works.
I have also tried using Blend Trees, but I cannot figure out how to do it.
I'm fairly new to Unity so a simple answer would be great.
open animator window
create 'State'
set animation clip into 'motion'
on top left click 'parameters' tab
click on plus sign next to parameters
click on 'Trigger'
name your trigger
right click on 'Any State' and make transition to drag a line to the new 'State' you created
click on the line between 'Any State' and the 'State' you created
under 'conditions' press the plus sign and add the trigger you just created
in code write
animator.SetTrigger("triggername");
when you want to transition to the before-mentioned animation state
repeat for all your animations, link them all from 'any state'

Unity2D my character jump more than one when i press jump key

https://pasteboard.co/IrKZbCV.png
void OnCollisionEnter2D(Collision2D col)
{
float angle = Vector3.Angle(Vector3.up, col.contacts[0].normal);
if (col.transform.gameObject.tag == "enemyWalk")
{
Physics2D.IgnoreCollision(col.gameObject.GetComponent<Collider2D>(), GetComponent<Collider2D>(), true);
}
else
{
Physics2D.IgnoreCollision(col.gameObject.GetComponent<Collider2D>(), GetComponent<Collider2D>(), false);
}
if (col.transform.gameObject.tag == "stone")
{
angle = Vector3.Angle(Vector3.up, col.contacts[0].normal);
if (Mathf.Approximately(angle, 0))
{
isGround = true;
taş = true;
}
}
else if (col.transform.gameObject.tag == "ground")
{
angle = Vector3.Angle(Vector3.up, col.contacts[0].normal);
if (Mathf.Approximately(angle, 0))
{
isGround = true;
çimen = true;
}
}
}
if ((isJump.jmp || Input.GetKeyDown(KeyCode.Space)) && !isDeath && isGround)
{
rgd.AddForce(new Vector2(0, 2.750f), ForceMode2D.Impulse);
jumpAudio.Play();
isGround = false;
}
İ want to jump my character only one times when i press jump key,but as i show this situation on picture,sometimes my character jumping too high when i jumped at near of the bottom of the rock.İ mean,as if my jump code working many times at same time.
i'm waiting for your helps.

Unity program stopped responding because of a infinite while loop

Hello stack overflow users! I was creating a game in unity 2018.2.2f1. All went great, but i missplaced the order of code lines in the program --> which caused a infite while loop appearing. I didn't know it would be infinite so I runned the program. Now my unity window is unselectable when i click on the icon, and when i enter the window, everything is frozen. I would close the program trough task manager, but i didnt save my files and i can't even save the project. Is there any way for me to save the project when it is in this state? My unity didn't crash, it just froze.
Here is my FIXED c# code if that somehow helps (and i am in visual studio):
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Movement : MonoBehaviour {
public float speed = 10f;
private Vector3 velocity = new Vector3();
private string direction = "none";
private bool canMoveAgain = true;
private bool go = false;
// Use this for initialization
void Start () {
speed = 10f;
}
// Update is called once per frame
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.collider.name == "wall (3)" && direction == "down")
{
go = false;
}
if (collision.collider.name == "wall (2)" && direction == "up")
{
go = false;
}
if (collision.collider.name == "wall" && direction == "left")
{
go = false;
}
if (collision.collider.name == "wall (1)" && direction == "right")
{
go = false;
}
}
void Update () {
if (Input.GetKeyDown(KeyCode.DownArrow) && canMoveAgain)
{
direction = "down";
go = true;
canMoveAgain = false;
while (go)
{
velocity = new Vector3(0,-1,0);
transform.position += velocity;
}
velocity = new Vector3(0, 0, 0);
direction = "none";
} else if (Input.GetKeyDown(KeyCode.UpArrow) && canMoveAgain)
{
direction = "up";
go = true;
canMoveAgain = false;
while (go)
{
velocity = new Vector3(0, +1, 0);
transform.position += velocity;
}
velocity = new Vector3(0, 0, 0);
direction = "none";
} else if (Input.GetKeyDown(KeyCode.LeftArrow) && canMoveAgain)
{
direction = "left";
go = true;
canMoveAgain = false;
while (go)
{
velocity = new Vector3(-1, 0, 0);
transform.position += velocity;
}
velocity = new Vector3(0, 0, 0);
direction = "none";
} else if (Input.GetKeyDown(KeyCode.RightArrow) && canMoveAgain)
{
direction = "right";
go = true;
canMoveAgain = false;
while (go)
{
velocity = new Vector3(+1, 0, 0);
transform.position += velocity;
}
velocity = new Vector3(0, 0, 0);
direction = "none";
}
}
}
You do
while (go)
{
velocity = new Vector3(+1, 0, 0);
transform.position += velocity;
}
but go is never set to false inside the loop.
OnCollisionEnter is never executed since the while is still being executed => freeze.
since Update is called each frame anyway you should rather move that part to a separate if(go) block after checking the Inputs ..
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.collider.name == "wall (3)" && direction == "down"
|| collision.collider.name == "wall (2)" && direction == "up"
|| collision.collider.name == "wall" && direction == "left"
|| collision.collider.name == "wall (1)" && direction == "right")
{
go = false;
velocity = Vector3.zero;
direction = "none"
}
}
void Update ()
{
if (Input.GetKeyDown(KeyCode.DownArrow) && canMoveAgain)
{
direction = "down";
go = true;
canMoveAgain = false;
velocity = -Vector3.up;
}
else if (Input.GetKeyDown(KeyCode.UpArrow) && canMoveAgain)
{
direction = "up";
go = true;
canMoveAgain = false;
velocity = Vector3.up;
}
else if (Input.GetKeyDown(KeyCode.LeftArrow) && canMoveAgain)
{
direction = "left";
go = true;
canMoveAgain = false;
velocity = -Vector3.right;
}
else if (Input.GetKeyDown(KeyCode.RightArrow) && canMoveAgain)
{
direction = "right";
go = true;
canMoveAgain = false;
velocity = Vector3.right;
}
if(go)
{
transform.position += velocity;
}
}
Note that currently your code is also frame rate dependent. You might want to rather use something like
public float moveSpeed;
...
transform.position += velocity * moveSpeed * Time.deltaTime;
For the direction I would rather recommend an enum like
private enum MoveDirection
{
None,
Up,
Down,
Left,
Right
}
and use it e.g. like
direction = MoveDirection.Up;
and
if(direction == MoveDirection.Up)
which is more efficient than comparing strings.
Note: Typed on smartphone so no warranty but I hope the idea gets clear
First of all. Do not close Unity.
You got two things you can try to do.
Luckily your code has a backup when you press run.
It is inside the Temp folder. The Temp folder will be replaced if you press run again. Copy the project to somewhere safe.
Attach a Debugger, this can be either Visual Studio or MonoDevelop. Once they are attached to Unity just click pause. And you're free to save your project.
I hope you find this answer before it's too late.

Categories

Resources