Shooting animation in Unity - c#

I'm creating shooting in Unity, I've set up everything but the problem is that I want the animation to play only on single click but in my script it plays animation infinitely while holding the button. Check the script below. Thanks.
public GameObject bulletPrefab;
public Transform firePoint;
private Animator anim;
// Start is called before the first frame update
void Start()
{
anim = GetComponent<Animator>();
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
Instantiate(bulletPrefab, firePoint.position, Quaternion.identity);
anim.SetBool("isShooting", true);
}
if (Input.GetKeyUp(KeyCode.Space))
{
anim.SetBool("isShooting", false);
}
}

Set 2 States with just Keys on time = 0 the end position Shooting and the end position idle. From idle to shooting with a trigger parameter. From shooting to idle just a time transition. Ps shooting can be done with multiple frames too. Hope it helps.

Related

2d Animation not playing second scene

I created a new animation for meteor GameObject , the animation functions in first scene normally, but the second scene is not playing regularly:
video explanation of the problem
I think the reason for this problem is timeScale , and I added this code from meteor object:
void Start()
{
Time.timeScale = 1f;
}
The problem is not fixed by this.
Animations are triggered by setting the value of an Animator object.
I.E.
[SerializeField] Animator anim;
void SetFields()
{
anim.SetBool("flagName", true);
anim.SetFloat("flagName", 0);
anim.SetInteger("flagName", 0);
}
In your first screen, you must have some script that is setting the field of your meteor animator which has not been added to your new scene

Unity animation not completing

i'm beginner on unity and game development. i'm trying to make a platformer game with unity, and i want to play a animation when the player is moving right or left, but the problem is that the isMoving variable for some reason is true animation is playing for a few moments (less than a second) and then is going to false again and the idle animation is playing.
My Animator (Exit time is disabled for all transitions):
My Movement script:
public class PlayerMovement : MonoBehaviour
{
private bool canPlayerJump;
private float horizontalInput;
private Animator animator;
// Start is called before the first frame update
void Start()
{
animator = GetComponent<Animator>();
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Space) && canPlayerJump)
{
GetComponent<Rigidbody>().AddForce(Vector3.up * 5, ForceMode.VelocityChange);
}
if (Input.GetKeyDown(KeyCode.D) || Input.GetKeyDown(KeyCode.A))
{
animator.SetBool("isMoving", true);
} else
{
animator.SetBool("isMoving", false);
}
horizontalInput = Input.GetAxis("Horizontal");
}
private void FixedUpdate()
{
GetComponent<Rigidbody>().velocity = new Vector3(horizontalInput * 5, GetComponent<Rigidbody>().velocity.y, 0);
}
private void OnCollisionEnter(Collision collision)
{
canPlayerJump = true;
Debug.Log(collision.gameObject.name);
}
private void OnCollisionExit(Collision collision)
{
canPlayerJump = false;
}
}
You using Update loop function that means this code will be executed each frame by unity. Similar to FixedUpdate, LateUpdate etc...
You can read more here: HERE
Once you pressing down you IF statement will be executed because you listening for BTN DOWN event. This means that TRUE will be returned only in one frame when you press actually button next frame it will return false. and your animations stops.
Try to change bool to Trigger
Or handle in another way bool var state.
Input.GetKeyDown
is only true in the one frame the button went down.
Returns true during the frame the user starts pressing down the key identified by the key KeyCode enum parameter.
You rather want to use Input.GetKey which stay true as long as the key stays pressed.
Returns true while the user holds down the key identified by the key KeyCode enum parameter
alternatively in order to not have redundant accesses you could also simply use
horizontalInput = Input.GetAxis("Horizontal");
animator.SetBool("isMoving", !Mathf.Approximately(horizontalInput, 0));
And as a general note: Cache the component references and don't use GetComponent over and over again!
[SerializeField] private Rigidbody _rigidbody;
private void Awake ()
{
if(!_rigodbody) _rigidbody = GetComponent<Rigidbody>();
}
then later everywhere use _rigidbdoy instead of GetComponent<Rigidbody>()

I'm creating an FPS game and I can't work out how to loop the shoot animation of the enemy I've attached the script to until my player dies

The script below is attached to the enemy on my game.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyMovement : MonoBehaviour {
private Animator attack;
Transform player;
UnityEngine.AI.NavMeshAgent nav;
void Awake()
{
player = GameObject.FindGameObjectWithTag("Player").transform;
nav = GetComponent<UnityEngine.AI.NavMeshAgent> ();
}
The code just below is getting the enemy to stop at a certain distance and shoot from the trigger "Attack". (Below and above are all the same code).
// Update is called once per frame
void Update () {
nav.SetDestination(player.position);
float distance = Vector3.Distance(this.transform.position, player.position);
if (distance < 10f)
{
Animator an = GetComponent<Animator>();
an.SetTrigger("Attack");
}
Debug.Log("distance" + distance);
}
}
This script basically uses the Nav Agent to make the enemy go towards my player and to start a shoot animation when the enemy is at a certain range.
Any help would be great. Thank you.
You should use a boolean for the check instead of a Trigger. You should change your code to set the boolean Attacking to false when the player is not in range and set the boolean to true when the player is in range for attacking. Also, make sure your animation clip loop is ticked on.

Unity bullet spawn

Where the bullet spawns when I shoot
Hi, for some reasons my bullet won't spawn where I tell it to.
The spawn point is at the end of my barrel, I take its transform position and rotation when I instantiate the bullet, but it spawns higher than the gun (way higher).
Here's the code that I have:
Animation anim; // Gun animation when shooting
AudioSource gunSound; // Gun sound when firing
public Rigidbody bullet; // I get the rigidbody of the bullet that will be spawned
public Transform spawnPoint; // The position of where it is supposed to spawn
void Start()
{
anim = GetComponent<Animation>();
gunSound = GetComponent<AudioSource>();
}
void Update()
{
if (Input.GetButtonDown("Fire1")) // If the left mouse button is clicked
{
Rigidbody bulletInstance;
bulletInstance = Instantiate(bullet, spawnPoint.position, spawnPoint.rotation) as Rigidbody; // This is where I don't understand why?!?!
bulletInstance.AddForce(spawnPoint.forward * 1000f);
gunSound.Play();
//anim.Play("GunShot4");
}
}
Help :)
It can happen, that the origin of the bullet is not at the middle of the model.

Despite Force Applied, No Movement

This code is for an elevator-type platform, where once the player stands on it, it 'takes' the player up by adding force onto it.
The thing is, while the force is created, the rigidbody (the player) does not move when the elevator moves. The code was written in C#, using Unity 5. In the code, the player is assigned the public 'rb', and contains a rigidbody.
The animation is a simple animation clip that moves the elevator up. Any ideas? Thank you for your time and answers in advance.
The elevator is Kinematic, the Player is not.
using UnityEngine;
using System.Collections;
/*This script activates when the player steps on the elevator, as it takes them up a floor.*/
public class ElevatorMovementScript : MonoBehaviour
{
private bool elevatorUp = false;
public Animation anim;
public int elevatorDelay = 5;
public int force = 800;
public Rigidbody rb;
// Use this for initialization
void Start ()
{
anim = GetComponent<Animation>();
}
// Update is called once per frame
void Update ()
{
}
/*Checks if the player has stepped onto the elevator. If the player has, it waits five seconds, and then pushes the player up.*/
void OnTriggerStay(Collider other)
{
if (other.gameObject.tag == "Player" && !elevatorUp)
{
Invoke("AnimationPlay",elevatorDelay);
elevatorUp = true;
}
}
/*Plays the animation of the player going up. Used for the 'Invoke' method.*/
void AnimationPlay()
{
rb.AddForce(transform.up * force);
Debug.Log (transform.up * force);
anim.Play ("Up");
}
}
It looks like this script is on your elevator's game object, in which case this line:
rb.AddForce(transform.up * force);
Will try to apply a force to the elevator, not the player. You've got to keep track of the player's rigidbody or somehow get it on demand in AnimationPlay.
You said that
the player is assigned the public 'rb'
But rb = GetComponent<Rigidbody>(); will ignore this and use the rigidbody attached to the gameobject that ElevatorMovementScript is attached to.

Categories

Resources