How to add the animations in my script in unity "C#"? - c#

I'm new to C#, I'm making a game to learn.
Can anyone help me, I found some scripts on the web for my player. I tried to make animations for it and I used the "Bool", but sometimes when the player starts to walk it doesn't get animated. What can I do?
I added the flip to flip the player left and right. And I added the "If" with the SetBool for the transition from "Idle" to "IsWalking".
Screenshot of my animator
My player has 4 scripts.
The other 3 are in the following link: [Link] (https://drive.google.com/drive/folders/1F_zbQJgihv82zjg5pcQ9L_dp0sgA2O2Q?usp=sharing)
using UnityEngine;
using System.Collections;
[RequireComponent (typeof (Player))]
public class PlayerInput : MonoBehaviour {
private Animator anim;
private bool m_FacingRight = true;
void Start () {
player = GetComponent<Player> ();
anim = GetComponent<Animator>();
}
void Update () {
Vector2 directionalInput = new Vector2 (Input.GetAxisRaw ("Horizontal"), Input.GetAxisRaw ("Vertical"));
player.SetDirectionalInput (directionalInput);
if (Input.GetAxisRaw("Horizontal") > 0 && !m_FacingRight)
{
Flip();
anim.SetBool("IsWalking", true);
}
if (Input.GetAxisRaw("Horizontal") < 0 && m_FacingRight)
{
Flip();
anim.SetBool("IsWalking", true);
}
if (Input.GetAxisRaw("Horizontal") == 0 && !m_FacingRight)
{
anim.SetBool("IsWalking", false);
}
if (Input.GetAxisRaw("Horizontal") == 0 && m_FacingRight)
{
anim.SetBool("IsWalking", false);
}
if (Input.GetKeyDown (KeyCode.Space)) {
player.OnJumpInputDown ();
anim.SetBool("IsJumping", true);
}
if (Input.GetKeyUp (KeyCode.Space)) {
player.OnJumpInputUp ();
anim.SetBool("IsJumping", false);
}
}
private void Flip()
{
// Switch the way the player is labelled as facing.
m_FacingRight = !m_FacingRight;
// Multiply the player's x local scale by -1.
Vector3 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
}
}}

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerInput : MonoBehaviour
{
private Animator anim;
private bool _right ;
private bool _left ;
public float MoveSpeed;
void Start()
{
anim = GetComponent<Animator>();
player = GetComponent<Player> ();
}
void Update()
{
Vector2 directionalInput = new Vector2(Input.GetAxisRaw("Horizontal")*Time.deltaTime, Input.GetAxisRaw("Vertical") * Time.deltaTime);
player.SetDirectionalInput (directionalInput);
if (Input.GetAxisRaw("Horizontal") > 0)
{
TurnRight();
anim.SetBool("IsWalking", true);
}
if (Input.GetAxisRaw("Horizontal") < 0)
{
TurnLeft();
anim.SetBool("IsWalking", true);
}
if (Input.GetAxisRaw("Horizontal") == 0)
{
anim.SetBool("IsWalking", false);
}
if (Input.GetKeyDown (KeyCode.Space)) {
player.OnJumpInputDown ();
anim.SetBool("IsJumping", true);
}
if (Input.GetKeyUp (KeyCode.Space)) {
player.OnJumpInputUp ();
anim.SetBool("IsJumping", false);
}
}
public void TurnRight()
{
if (_right) return;
transform.localScale = new Vector3(Mathf.Abs(transform.localScale.x), transform.localScale.y, 0);
_right = true;
_left = false;
}
public void TurnLeft()
{
if (_left) return;
transform.localScale = new Vector3(-transform.localScale.x, transform.localScale.y, 0);
_left = true;
_right = false;
}
}
there is some problems in your script.
For Example Once I start moving right, m_FacingRight will be true, and then I stop moving. Still, m_FacingRight is true. Since m_FacingRight is still true, if I start moving to the right again, the animation of walk will not play. Because you have used
if (Input.GetAxisRaw("Horizontal") > 0 && !m_FacingRight)
Same for the left side

Related

Changing a game objects velocity on button press in unity

So I'm trying to add a dash mechanic to a game character im building. However for some reason i can't get the game objects velocity to actually change. I tried using addForce which worked, but i had to add a lot in order to get the desired effect and that behaved strangely sometimes!
Do i need to do anything else to the game objects velocity than i already doing?
Heres my script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public float dashSpeed;
private int dashDirection;
private float dashCoolDown;
public float startDashCoolDown;
private float dashTime;
public float startDashTime;
public GameObject dashEffect;
public float speed;
public float jumpForce;
private float moveInput;
private Rigidbody2D rb;
private bool isFacingRight = true;
private Animator anim;
private bool isGrounded;
public Transform groundCheck;
public float checkRadius;
public LayerMask whatIsGround;
private int extraJumps;
public int extraJumpsValue;
public GameObject dustEffect;
public GameObject trailEffect;
private void Awake()
{
// Setting up references.
isGrounded = transform.Find("GroundCheck");
anim = GetComponent<Animator>();
rb = GetComponent<Rigidbody2D>();
}
void Start()
{
extraJumps = extraJumpsValue;
rb = GetComponent<Rigidbody2D>();
dashTime = startDashTime;
dashCoolDown = startDashCoolDown;
}
void FixedUpdate()
{
isGrounded = false;
// Check to see if grounded
Collider2D[] colliders = Physics2D.OverlapCircleAll(groundCheck.position, checkRadius, whatIsGround);
for (int i = 0; i < colliders.Length; i++)
{
if (colliders[i].gameObject != gameObject)
{
isGrounded = true;
anim.SetBool("Ground", isGrounded);
}
}
// Check if movement is allowed
if (!GameMaster.disableMovement)
{
// Move character
moveInput = Input.GetAxis("Horizontal");
rb.velocity = new Vector2(moveInput * speed, rb.velocity.y);
Instantiate(trailEffect, groundCheck.position, Quaternion.identity);
anim.SetFloat("Speed", Mathf.Abs(moveInput));
}
// Flip character
if (isFacingRight == false && moveInput > 0)
{
Flip();
}
else if (isFacingRight == true && moveInput < 0)
{
Flip();
}
}
private void Update()
{
// Check if the player is grounded
if (isGrounded == true)
{
extraJumps = extraJumpsValue;
}
// Check if movement is allowed
if (!GameMaster.disableMovement)
{
// Check for jump
// If the player has more than one jump available
if (Input.GetKeyDown(KeyCode.Space) && extraJumps > 0)
{
isGrounded = false;
anim.SetBool("Ground", isGrounded);
rb.velocity = Vector2.up * jumpForce;
extraJumps--;
Instantiate(dustEffect, groundCheck.position, Quaternion.identity);
}
// If the player only has one jump available
if (Input.GetKeyDown(KeyCode.Space) && extraJumps == 0 && isGrounded == true)
{
isGrounded = false;
anim.SetBool("Ground", isGrounded);
rb.velocity = Vector2.up * jumpForce;
}
// Check for dash
if (dashCoolDown <= 0)
{
if (Input.GetKeyDown(KeyCode.LeftShift))
{
anim.SetBool("Dash", true);
Dash();
dashTime = startDashTime;
}
}
else
{
dashCoolDown -= Time.deltaTime;
}
}
}
void Dash()
{
if (dashTime <= 0)
{
dashCoolDown = startDashCoolDown;
anim.SetBool("Dash", false);
}
else
{
dashTime -= Time.deltaTime;
if (isFacingRight)
{
rb.velocity = Vector2.right * dashSpeed;
}
else if (!isFacingRight)
{
rb.velocity = Vector2.left * dashSpeed;
}
}
}
void Flip()
{
isFacingRight = !isFacingRight;
// Multiply the player's x local scale by -1.
Vector3 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
}
}
If you dont get the desired dash effect with Rigidbody.velocity, you can try using Rigidbody.addForce(). I know you said you already used it, but there are multiple different force modes you can apply here. I would suggest using this one, because it applies full force from the start and then drops it off. You can read more about it yourself here.
So you could modify your code like so:
void Dash()
{
if (isFacingRight)
{
rb.AddForce(Vector2.right*dashSpeed, ForceMode.VelocityChange);
}
else if (!isFacingRight)
{
rb.AddForce(Vector2.left*dashSpeed, ForceMode.VelocityChange);
}
}
Note, that you also dont need to call dash repeatedly to falloff the velocity. this function should now be only called onse the button to dash (shift) has been pressed.
Hope this helped!

gameobjects on switch statement(col.tag)

im developing a game right now. It seems more like capture the flag in 2d. But im having problem with my character script. what i want is if my character has the flag and he goes back to her base with a flag(gameobject on) she will go to the winscene. but the thing is i also want her to not proceed to the winscene when the gameobject is not on.
Here's the Script
GameObject[] toEnable, toDisable;
public GameObject CharFlag;
private Rigidbody2D rb;
private Animator anim;
private float moveSpeed;
private float dirX;
private bool facingRight = true;
private Vector3 localScale;
//Use this for Initialization
private void Start(){
rb = GetComponent<Rigidbody2D>();
anim = GetComponent<Animator>();
localScale = transform.localScale;
moveSpeed = 5f;
// Finding game objects with tags "ToEnable" and "ToDisable"
toEnable = GameObject.FindGameObjectsWithTag ("CharFlag");
// Disabling game objects with tag "ToEnable"
foreach (GameObject element in toEnable)
{
element.gameObject.SetActive (false);
}
}
//Update is called once per frame
private void Update()
{
dirX = CrossPlatformInputManager.GetAxisRaw ("Horizontal") * moveSpeed;
if (CrossPlatformInputManager.GetButtonDown ("Jump") && rb.velocity.y == 0)
rb.AddForce(Vector2.up * 700f);
if (Mathf.Abs(dirX) > 0 && rb.velocity.y == 0)
anim.SetBool("isRunning", true);
else
anim.SetBool("isRunning", false);
if (rb.velocity.y == 0)
{
anim.SetBool("isJumping", false);
anim.SetBool("isFalling", false);
}
if (rb.velocity.y > 0)
{
anim.SetBool("isJumping", true);
}
if (rb.velocity.y < 0)
{
anim.SetBool("isJumping", false);
anim.SetBool("isFalling", true);
}
}
private void FixedUpdate()
{
rb.velocity = new Vector2(dirX, rb.velocity.y);
}
private void LateUpdate()
{
if (dirX > 0)
facingRight = true;
else if (dirX < 0)
facingRight = false;
if (((facingRight) && (localScale.x < 0)) || ((!facingRight) && (localScale.x > 0)))
localScale.x *= -1;
transform.localScale = localScale;
}
void OnTriggerEnter2D (Collider2D col)
{
switch (col.tag) {
case "EnemyField":
CharFlag.gameObject.SetActive (true);
break;
case "AlyField":
SceneManager.LoadScene ("YouWin");
break;
}
}
}
This would be better as a comment but I only have 40 reputation.
Simply check if the GameObject is active or not.
switch (col.tag)
{
case "EnemyField":
CharFlag.gameObject.SetActive (true);
break;
case "AllyField":
if(CharFlag.gameObject.activeSelf)
{
SceneManager.LoadScene ("YouWin");
}
break;

Unity 2D: How to make patrolling AI turn around?

I'm making a 2D platformer in Unity, and made a patrolling enemy with code from a tutorial video. The enemy basically moves randomly to different spots in the scene. But how can I make the sprite turn around?
This is my code so far. I've tried with different approaches, but not getting the expected behavior.
public float speed = 10f;
private float waitTime;
public float startWaitTime = 1f;
public Transform[] moveSpots;
private int randomSpot;
private bool moving = true;
private bool m_FacingRight = true;
void Start()
{
waitTime = startWaitTime;
randomSpot = Random.Range(0, moveSpots.Length);
}
void Update()
{
transform.position = Vector2.MoveTowards(transform.position, moveSpots[randomSpot].position, speed * Time.deltaTime);
if (Vector2.Distance(transform.position, moveSpots[randomSpot].position) < 0.2f)
{
//Debug.Log(m_FacingRight);
// if (moving.x > 0 && !m_FacingRight)
// {
// Debug.Log("moving right");
// Flip();
// }
// else if (moving.x < 0 && m_FacingRight)
// {
// Debug.Log("moving left");
// Flip();
// }
if (waitTime <= 0)
{
//moving = true;
randomSpot = Random.Range(0, moveSpots.Length);
waitTime = startWaitTime;
}
else
{
//moving = false;
waitTime -= Time.deltaTime;
}
}
}
//private void Flip()
//{
//m_FacingRight = !m_FacingRight;
//transform.Rotate(0f, 180f, 0f);
//}
**********************************EDIT****************************************
I ended up with this for the enemy script movement
private bool facingRight = true;
private Rigidbody2D rigidBody2D;
private SpriteRenderer spriteRenderer;
public Vector2 speed = new Vector2(10, 0);
public Vector2 direction = new Vector2(1, 0);
private void Awake()
{
rigidBody2D = GetComponent<Rigidbody2D>();
spriteRenderer = GetComponent<SpriteRenderer>();
}
void OnCollisionEnter2D(Collision2D collision)
{
if (collision.collider.CompareTag("Wall") || collision.collider.CompareTag("Player"))
{
direction = Vector2.Scale(direction, new Vector2(-1, 0));
}
if (!collision.collider.CompareTag("Ground"))
{
if (!facingRight)
{
Flip();
}
else if (facingRight)
{
Flip();
}
}
}
void FixedUpdate()
{
Vector2 movement = new Vector2(speed.x * direction.x, 0);
movement *= Time.deltaTime;
transform.Translate(movement);
}
private void Flip()
{
facingRight = !facingRight;
if (!facingRight)
{
spriteRenderer.flipX = true;
}
else if (facingRight)
{
spriteRenderer.flipX = false;
}
}
Rewrite your Flip function to
private void Flip()
{
m_FacingRight = !m_FacingRight;
GetComponent<SpriteRenderer>().flipX = true;
}
Also, if you're looking for a reference, I made a platformer in Unity that includes enemy patrolling https://github.com/sean244/Braid-Clone
In a sidescroller, an easy way to achieve this is to use SpriteRenderer.flipX.
For instance, if you want to flip X when the velocity is negative:
var sr = GetComponent<SpriteRenderer>();
sr.flipX = velocity.x < 0;

Unity2D: How to make my player invulnerable for X amount of time?

I want to make my player invulnerable from objects hitting him for a few seconds after he resets back to the center of the game, meaning I don't want anything to hurt him and I don't want the player to move for 5 seconds, but i'm not sure of how to do that! I searched it up but results that I found doesn't match up with my code. Anyway this is my playermovement script:
private Animator anim;
public float speed = 15f;
public static Vector3 target;
private bool touched;
private bool canmove;
Vector3 startPosition;
void Start () {
target = transform.position;
anim = GetComponent<Animator> ();
}
void Update () {
if (Input.GetMouseButtonDown (0)) {
Vector3 mousePosition = Input.mousePosition;
mousePosition.z = 10; // distance from the camera
target = Camera.main.ScreenToWorldPoint(mousePosition);
target.z = transform.position.z;
}
transform.position = Vector3.MoveTowards (transform.position, target, speed * Time.deltaTime);
var movementDirection = (target - transform.position).normalized;
if (movementDirection.x != 0 || movementDirection.y != 0) {
anim.SetBool ("walking", false);
anim.SetFloat("SpeedX", movementDirection.x);
anim.SetFloat("SpeedY", movementDirection.y);
anim.SetBool ("walking", true);
}
}
void FixedUpdate () {
float LastInputX = transform.position.x - target.x;
float LastInputY = transform.position.y - target.y;
if (touched) {
if (LastInputX != 0 || LastInputY != 0) {
anim.SetBool ("walking", true);
if (LastInputX < 0) {
anim.SetFloat ("LastMoveX", 1f);
} else if (LastInputX > 0) {
anim.SetFloat ("LastMoveX", -1f);
} else {
anim.SetFloat ("LastMoveX", 0f);
}
if (LastInputY > 0) {
anim.SetFloat ("LastMoveY", 1f);
} else if (LastInputY < 0) {
anim.SetFloat ("LastMoveY", -1f);
} else {
anim.SetFloat ("LastMoveY", 0f);
}
}
}else{
touched = false;
anim.SetBool ("walking", false);
}
}
}
And this is my player health script:
public int curHealth;
public int maxHealth = 3;
Vector3 startPosition;
bool invincible = false;
void Start ()
{
curHealth = maxHealth;
startPosition = transform.position;
}
void Update ()
{
if (curHealth > maxHealth) {
curHealth = maxHealth;
}
if (curHealth <= 0) {
Die ();
}
}
void Die ()
{
//Restart
Application.LoadLevel (Application.loadedLevel);
}
public void Damage(int dmg)
{
curHealth -= dmg;
Reset();
}
void Reset ()
{
transform.position = startPosition;
PlayerMovement.target = startPosition;
}
}
So to be more simple, I want to make my player invulnerable (once he reset back in the center of the screen) from getting hit from enemies for 5 seconds and people who are playing my player can not move for 5 seconds. Thank you! (My game is a topdown 2d click to move game)
I think this should do the trick. At least point you in the right direction.
Simple explanation, i changed invincible to be a time, a time in the future.
Then we simply add a time in the future to it at some event, and from that event onward to the point in the future we want him invincible.
So at every event where he would take damage we check, is now in the future of invincible or is invincible in the future of now. that is your bool.
DateTime invincible = DateTime.Now;
public void Damage(int dmg)
{
if(invincible <= DateTime.Now)
{
curHealth -= dmg;
Reset();
}
}
void Reset ()
{
transform.position = startPosition;
PlayerMovement.target = startPosition;
invincible = DateTime.Now.AddSeconds(5);
}
if you want a helper method like this
bool IsInvincible(){
return invincible <= DateTime.Now;
}
Then you can change out the if(invincible <= DateTime.Now) with if(IsInvincible()) in your public void Damage(int dmg)
In game development, you have to keep in mind that everything happens within a frame update. I like to use coroutines to implement invincibility frames in Unity. A coroutine is simply a method that runs in parallel to the main update loop and resumes where it left off in the next update.
float dmg = 100.0f;
bool isHitByEnemy = false
bool isInvulnerable = false
void Demage()
{
//some dmg logic
if (isHitByEnemy && isInvulnerable == false)
{
StartCoroutine("OnInvulnerable");
}
}
IEnumerator OnInvulnerable()
{
isInvulnerable = true;
dmg = 0.0f;
yield return new WaitForSeconds(0.5f); //how long player invulnerable
dmg = 100.0f;
isInvulnerable = false;
}

Unity Click on 1 object to trigger another object

Please keep in mind that I'm new to Unity. I have 2 script that I want to "combline" but when I try then it don't Work.
I have a Script (Name : RobotController). This script controls the movement of the player. Up/Jump, Down, Left and Right. (This Works with Keyboard keys only atm)
This script Works just fine but now I want to add the feature of touch keys for phone. With this I mean that if a person click on the "up-Arrow" the player shall jump.
The Up-Arrow is an object.
This is were I get my problem. I have created the Up-Arrow with a collider and a script.
Up-Arrow script:
public class NewJumpScript : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
void OnMouseOver()
{
if ((Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began) || (Input.GetMouseButtonDown(0)))
{
Debug.Log("test");
}
}
}
Here is the RobotController script´, with ground check and so on.
public class RobotController : MonoBehaviour {
//This will be our maximum speed as we will always be multiplying by 1
public float maxSpeed = 2f;
public GameObject player;
public GameObject sprite;
//a boolean value to represent whether we are facing left or not
bool facingLeft = true;
//a value to represent our Animator
Animator anim;
//to check ground and to have a jumpforce we can change in the editor
bool grounded = true;
public Transform groundCheck;
public float groundRadius = 1f;
public LayerMask whatIsGround;
public float jumpForce = 300f;
private bool isOnGround = false;
void OnCollisionEnter2D(Collision2D collision) {
isOnGround = true;
}
void OnCollisionExit2D(Collision2D collision) {
anim.SetBool ("Ground", grounded);
anim.SetFloat ("vSpeed", rigidbody2D.velocity.y);
isOnGround = false;
}
// Use this for initialization
void Start () {
player = GameObject.Find("player");
//set anim to our animator
anim = GetComponent <Animator>();
}
void FixedUpdate () {
//set our vSpeed
//set our grounded bool
grounded = Physics2D.OverlapCircle (groundCheck.position, groundRadius, whatIsGround);
//set ground in our Animator to match grounded
anim.SetBool ("Ground", grounded);
float move = Input.GetAxis ("Horizontal");//Gives us of one if we are moving via the arrow keys
//move our Players rigidbody
rigidbody2D.velocity = new Vector3 (move * maxSpeed, rigidbody2D.velocity.y);
//set our speed
anim.SetFloat ("Speed",Mathf.Abs (move));
//if we are moving left but not facing left flip, and vice versa
if (move > 0 && !facingLeft) {
Flip ();
} else if (move < 0 && facingLeft) {
Flip ();
}
}
void Update(){
if ((isOnGround == true && Input.GetKeyDown (KeyCode.UpArrow)) || (isOnGround == true && Input.GetKeyDown (KeyCode.Space))) {
anim.SetBool("Ground",false);
rigidbody2D.AddForce (new Vector2 (0, jumpForce));
}
if (isOnGround == true && Input.GetKeyDown (KeyCode.DownArrow))
{
gameObject.transform.localScale = new Vector3(transform.localScale.x, 0.2f, 0.2f);
}
if (isOnGround == true && Input.GetKeyUp (KeyCode.DownArrow))
{
gameObject.transform.localScale = new Vector3(transform.localScale.x, 0.3f, 0.3f);
}
}
//flip if needed
void Flip(){
facingLeft = !facingLeft;
Vector3 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
}
}
What needs to happen is that when The "Up-arrow" in the game is clicked then The person shall jump on the same tearms as in the RobotController script.
I hope you understand my question.
Thanks for your time and help.
I posted this same answer to both of the questions, because they are so similar. You can easily modify the code to your needs.
This is only one way to do it. There are probably many more, but this is the best I have encountered so far.
On the QUI button, script like this is needed:
private Mover playerMover;
void Start()
{
playerMover = GameObject.Find("Character").GetComponent<Mover>();
}
void OnMouseOver()
{
if (Input.GetMouseButton(0))
{
Debug.Log("pressed");
playerMover.MoveButtonPressed();
}
}
Notice that find is only done ones in start function, because it is computationally heavy.
And on the Character gameobject, script component like this is needed:
using UnityEngine;
using System.Collections;
public class Mover : MonoBehaviour {
public void MoveButtonPressed()
{
lastPressedTime = Time.timeSinceLevelLoad;
}
public double moveTime = 0.1;
private double lastPressedTime = 0.0;
void Update()
{
if(lastPressedTime + moveTime > Time.timeSinceLevelLoad)
{
// Character is moving
rigidbody.velocity = new Vector3(1.0f, 0.0f, 0.0f);
}
else
{
rigidbody.velocity = new Vector3(0.0f, 0.0f, 0.0f);
}
}
}

Categories