I imported Unity Standard Assets cross platform input successfully
In imported cross Platfrom script UnityStandardAssets.CrossCrossPlatformInput is working perfectly
but when i use it in CharacterController2D script that not respoonding
shows errors
unknown package actually namespace in C#
and in file path for standard assets is
Assets\Standard Assets\CrossPlatformInput\Scripts
and CharacterController2D path is
Assets\Scripts
following CharacterController2D script is
using UnityEngine;
using System.Collections;
using UnityEngine.SceneManagement; // include so we can load new scenes
using UnityStandardAssets.CrossCrossPlatformInput; //even this line shows error
public class CharacterController2D : MonoBehaviour {
// player controls
[Range(0.0f, 10.0f)] // create a slider in the editor and set limits on moveSpeed
public float moveSpeed = 3f;
public float jumpForce = 600f;
// player health
public int playerHealth = 1;
// LayerMask to determine what is considered ground for the player
public LayerMask whatIsGround;
// Transform just below feet for checking if player is grounded
public Transform groundCheck;
// player can move?
// we want this public so other scripts can access it but we don't want to show in editor as it might confuse designer
[HideInInspector]
public bool playerCanMove = true;
// SFXs
public AudioClip coinSFX;
public AudioClip deathSFX;
public AudioClip fallSFX;
public AudioClip jumpSFX;
public AudioClip victorySFX;
// private variables below
// store references to components on the gameObject
Transform _transform;
Rigidbody2D _rigidbody;
Animator _animator;
AudioSource _audio;
// hold player motion in this timestep
float _vx;
float _vy;
// player tracking
bool facingRight = true;
bool isGrounded = false;
bool isRunning = false;
bool canDoubleJump = false;
// store the layer the player is on (setup in Awake)
int _playerLayer;
// number of layer that Platforms are on (setup in Awake)
int _platformLayer;
void Awake () {
// get a reference to the components we are going to be changing and store a reference for efficiency purposes
_transform = GetComponent<Transform> ();
_rigidbody = GetComponent<Rigidbody2D> ();
if (_rigidbody==null) // if Rigidbody is missing
Debug.LogError("Rigidbody2D component missing from this gameobject");
_animator = GetComponent<Animator>();
if (_animator==null) // if Animator is missing
Debug.LogError("Animator component missing from this gameobject");
_audio = GetComponent<AudioSource> ();
if (_audio==null) { // if AudioSource is missing
Debug.LogWarning("AudioSource component missing from this gameobject. Adding one.");
// let's just add the AudioSource component dynamically
_audio = gameObject.AddComponent<AudioSource>();
}
// determine the player's specified layer
_playerLayer = this.gameObject.layer;
// determine the platform's specified layer
_platformLayer = LayerMask.NameToLayer("Platform");
}
// this is where most of the player controller magic happens each game event loop
void Update()
{
// exit update if player cannot move or game is paused
if (!playerCanMove || (Time.timeScale == 0f))
return;
// determine horizontal velocity change based on the horizontal input
_vx = CrossPlatformInputManager.GetAxisRaw ("Horizontal");
// Determine if running based on the horizontal movement
if (_vx != 0)
{
isRunning = true;
} else {
isRunning = false;
}
// set the running animation state
_animator.SetBool("Running", isRunning);
// get the current vertical velocity from the rigidbody component
_vy = _rigidbody.velocity.y;
// Check to see if character is grounded by raycasting from the middle of the player
// down to the groundCheck position and see if collected with gameobjects on the
// whatIsGround layer
isGrounded = Physics2D.Linecast(_transform.position, groundCheck.position, whatIsGround);
///checking if can do double jump or not
if (isGrounded)
{
canDoubleJump = true;
}
// Set the grounded animation states
_animator.SetBool("Grounded", isGrounded);
if(isGrounded && CrossPlatformInputManager.GetButtonDown("Jump")) // If grounded AND jump button pressed, then allow the player to jump
{
doJump ();
}
else if(canDoubleJump && CrossPlatformInputManager.GetButtonDown("Jump"))
{
doJump ();
canDoubleJump = false; //disabling dpuble jump after single jump
}
// If the player stops jumping mid jump and player is not yet falling
// then set the vertical velocity to 0 (he will start to fall from gravity)
if(CrossPlatformInputManager.GetButtonUp("Jump") && _vy>0f)
{
_vy = 0f;
}
// Change the actual velocity on the rigidbody
_rigidbody.velocity = new Vector2(_vx * moveSpeed, _vy);
// if moving up then don't collide with platform layer
// this allows the player to jump up through things on the platform layer
// NOTE: requires the platforms to be on a layer named "Platform"
Physics2D.IgnoreLayerCollision(_playerLayer, _platformLayer, (_vy > 0.0f));
}
// Checking to see if the sprite should be flipped
// this is done in LateUpdate since the Animator may override the localScale
// this code will flip the player even if the animator is controlling scale
void LateUpdate()
{
// get the current scale
Vector3 localScale = _transform.localScale;
if (_vx > 0) // moving right so face right
{
facingRight = true;
} else if (_vx < 0) { // moving left so face left
facingRight = false;
}
// check to see if scale x is right for the player
// if not, multiple by -1 which is an easy way to flip a sprite
if (((facingRight) && (localScale.x<0)) || ((!facingRight) && (localScale.x>0))) {
localScale.x *= -1;
}
// update the scale
_transform.localScale = localScale;
}
// if the player collides with a MovingPlatform, then make it a child of that platform
// so it will go for a ride on the MovingPlatform
void OnCollisionEnter2D(Collision2D other)
{
if (other.gameObject.tag=="MovingPlatform")
{
this.transform.parent = other.transform;
}
}
// if the player exits a collision with a moving platform, then unchild it
void OnCollisionExit2D(Collision2D other)
{
if (other.gameObject.tag=="MovingPlatform")
{
this.transform.parent = null;
}
}
// do what needs to be done to freeze the player
void FreezeMotion() {
playerCanMove = false;
_rigidbody.isKinematic = true;
}
// do what needs to be done to unfreeze the player
void UnFreezeMotion() {
playerCanMove = true;
_rigidbody.isKinematic = false;
}
// play sound through the audiosource on the gameobject
void PlaySound(AudioClip clip)
{
_audio.PlayOneShot(clip);
}
// public function to apply damage to the player
public void ApplyDamage (int damage) {
if (playerCanMove) {
playerHealth -= damage;
if (playerHealth <= 0) { // player is now dead, so start dying
PlaySound(deathSFX);
StartCoroutine (KillPlayer ());
}
}
}
//Public Jump function
public void doJump()
{
// reset current vertical motion to 0 prior to jump
_vy = 0f;
// add a force in the up direction
_rigidbody.AddForce (new Vector2 (0, jumpForce));
// play the jump sound
PlaySound(jumpSFX);
}
//EnemyJump function
public void EnemyJump()
{
doJump ();
}
// public function to kill the player when they have a fall death
public void FallDeath () {
if (playerCanMove) {
playerHealth = 0;
PlaySound(fallSFX);
StartCoroutine (KillPlayer ());
}
}
// coroutine to kill the player
IEnumerator KillPlayer()
{
if (playerCanMove)
{
// freeze the player
FreezeMotion();
// play the death animation
_animator.SetTrigger("Death");
// After waiting tell the GameManager to reset the game
yield return new WaitForSeconds(2.0f);
if (GameManager.gm) // if the gameManager is available, tell it to reset the game
GameManager.gm.ResetGame();
else // otherwise, just reload the current level
SceneManager.LoadScene(SceneManager.GetActiveScene().name);
}
}
public void CollectCoin(int amount) {
PlaySound(coinSFX);
if (GameManager.gm) // add the points through the game manager, if it is available
GameManager.gm.AddPoints(amount);
}
// public function on victory over the level
public void Victory() {
PlaySound(victorySFX);
FreezeMotion ();
_animator.SetTrigger("Victory");
if (GameManager.gm) // do the game manager level compete stuff, if it is available
GameManager.gm.LevelCompete();
}
// public function to respawn the player at the appropriate location
public void Respawn(Vector3 spawnloc) {
UnFreezeMotion();
playerHealth = 1;
_transform.parent = null;
_transform.position = spawnloc;
_animator.SetTrigger("Respawn");
}
}
This is first time that I have used cross platform input
so I don't even know why this error is showing
Sorry to Bother you guys.
I think i found my error in this code
actually i mistakenly write
using UnityStandardAssets.CrossCrossPlatformInput;
instead of
using UnityStandardAssets.CrossPlatformInput;
that's why it's showing error Unknown Namespace Under Standard Unity Assests
Actually I am new to Unity and also new to game development
i think that's why this problem happen
also, you need to use a compiler definition as shown, i was stuck on it for a long time, but found it written in the guidelines that come along with standard asset package..
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityStandardAssets.CrossPlatformInput;
// CROSS_PLATFORM_INPUT
public class Player : MonoBehaviour
{
public float speed = 6f;
Vector2 moveVelocity;
public Rigidbody2D rb;
Vector2 movement;
void Update()
{
Vector2 moveInput = new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"));
moveVelocity = moveInput * speed;
}
void FixedUpdate()
{
rb.MovePosition(rb.position + moveVelocity * Time.fixedDeltaTime);
}
public void Up()
{
FixedUpdate();
}
private void OnTriggerEnter2D(Collider2D target)
{
if (target.tag == "Enemy")
{
GameManager.instance.PlayerDied();
Debug.Log("ok");
}
if (target.tag == "Finish")
{
Debug.Log("ok");
GameManager.instance.PlayerWin();
}
}
}
Related
i am following a brackeys tutorial, the sprite is moving left right but not jumping. "Jump" is working fine but the results are not present in the gameview.it references a script provided by brackeys but i dont whether thats the problem.
Here is the code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class player_movemnt : MonoBehaviour
{
public CharacterController2D controller;
float horizontal_movement =0f;
public float run_speed = 60f;
bool jump = false;
void Update()
{
horizontal_movement = Input.GetAxisRaw("Horizontal")*run_speed;
if(Input.GetButtonDown("Jump"))
{
jump = true;
Debug.Log("l");
}
}
void FixedUpdate()
{
//move character
controller.Move(horizontal_movement*Time.fixedDeltaTime,false, jump);
jump= false;
}
}
here is the CharacterControl2D scrip
using UnityEngine;
using UnityEngine.Events;
public class CharacterController2D : MonoBehaviour
{
[SerializeField] private float m_JumpForce = 400f; // Amount of force added when the player jumps.
[Range(0, 1)] [SerializeField] private float m_CrouchSpeed = .36f; // Amount of maxSpeed applied to crouching movement. 1 = 100%
[Range(0, .3f)] [SerializeField] private float m_MovementSmoothing = .05f; // How much to smooth out the movement
[SerializeField] private bool m_AirControl = false; // Whether or not a player can steer while jumping;
[SerializeField] private LayerMask m_WhatIsGround; // A mask determining what is ground to the character
[SerializeField] private Transform m_GroundCheck; // A position marking where to check if the player is grounded.
[SerializeField] private Transform m_CeilingCheck; // A position marking where to check for ceilings
[SerializeField] private Collider2D m_CrouchDisableCollider; // A collider that will be disabled when crouching
const float k_GroundedRadius = .2f; // Radius of the overlap circle to determine if grounded
private bool m_Grounded; // Whether or not the player is grounded.
const float k_CeilingRadius = .2f; // Radius of the overlap circle to determine if the player can stand up
private Rigidbody2D m_Rigidbody2D;
private bool m_FacingRight = true; // For determining which way the player is currently facing.
private Vector3 m_Velocity = Vector3.zero;
[Header("Events")]
[Space]
public UnityEvent OnLandEvent;
[System.Serializable]
public class BoolEvent : UnityEvent<bool> { }
public BoolEvent OnCrouchEvent;
private bool m_wasCrouching = false;
private void Awake()
{
m_Rigidbody2D = GetComponent<Rigidbody2D>();
if (OnLandEvent == null)
OnLandEvent = new UnityEvent();
if (OnCrouchEvent == null)
OnCrouchEvent = new BoolEvent();
}
private void FixedUpdate()
{
bool wasGrounded = m_Grounded;
m_Grounded = false;
// The player is grounded if a circlecast to the groundcheck position hits anything designated as ground
// This can be done using layers instead but Sample Assets will not overwrite your project settings.
Collider2D[] colliders = Physics2D.OverlapCircleAll(m_GroundCheck.position, k_GroundedRadius, m_WhatIsGround);
for (int i = 0; i < colliders.Length; i++)
{
if (colliders[i].gameObject != gameObject)
{
m_Grounded = true;
if (!wasGrounded)
OnLandEvent.Invoke();
}
}
}
public void Move(float move, bool crouch, bool jump)
{
// If crouching, check to see if the character can stand up
if (!crouch)
{
// If the character has a ceiling preventing them from standing up, keep them crouching
if (Physics2D.OverlapCircle(m_CeilingCheck.position, k_CeilingRadius, m_WhatIsGround))
{
crouch = true;
}
}
//only control the player if grounded or airControl is turned on
if (m_Grounded || m_AirControl)
{
// If crouching
if (crouch)
{
if (!m_wasCrouching)
{
m_wasCrouching = true;
OnCrouchEvent.Invoke(true);
}
// Reduce the speed by the crouchSpeed multiplier
move *= m_CrouchSpeed;
// Disable one of the colliders when crouching
if (m_CrouchDisableCollider != null)
m_CrouchDisableCollider.enabled = false;
} else
{
// Enable the collider when not crouching
if (m_CrouchDisableCollider != null)
m_CrouchDisableCollider.enabled = true;
if (m_wasCrouching)
{
m_wasCrouching = false;
OnCrouchEvent.Invoke(false);
}
}
// Move the character by finding the target velocity
Vector3 targetVelocity = new Vector2(move * 10f, m_Rigidbody2D.velocity.y);
// And then smoothing it out and applying it to the character
m_Rigidbody2D.velocity = Vector3.SmoothDamp(m_Rigidbody2D.velocity, targetVelocity, ref m_Velocity, m_MovementSmoothing);
// If the input is moving the player right and the player is facing left...
if (move > 0 && !m_FacingRight)
{
// ... flip the player.
Flip();
}
// Otherwise if the input is moving the player left and the player is facing right...
else if (move < 0 && m_FacingRight)
{
// ... flip the player.
Flip();
}
}
// If the player should jump...
if (m_Grounded && jump)
{
// Add a vertical force to the player.
m_Grounded = false;
m_Rigidbody2D.AddForce(new Vector2(0f, m_JumpForce));
}
}
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;
}
}
i am completely dumbfounded with this problem.
If you're using a separate class to handle your movement, it's always ideal to include it alongside your question. So others wont have to search for it.
Your code appears okay, at least based on the tutorial you've mentioned. Double-check that them_GroundCheck GameObject of CharacterController2D is on the ground rather than on the bottom of the player, as that's responsible for ensuring you can jump in the first place.
public CharacterController2D characterController;
public float runSpeed = 60f;
private float _horizontalMovement;
private bool _jump;
private void Update()
{
_horizontalMovement = Input.GetAxisRaw("Horizontal") * runSpeed;
if (Input.GetButtonDown("Jump"))
{
_jump = true;
}
}
private void FixedUpdate()
{
characterController.Move(_horizontalMovement * Time.fixedDeltaTime, false, _jump);
_jump = false;
}
I'd recommend working backwards and ensuring your CharacterController2D is set up correctly to support the jump, including any attributes you need to add in the inspector window. Such as a reference to GroundCheck and its LayerMask.
I'm making a 2D game in Unity, which has falling platforms that the player can "ride" down. I want the player to still be able to move left or right (ie horizontally) while standing on a falling platform. Without additional code, just using the Rigidbody physics, the player does fall along with the platform, but the falling is choppy, and the game doesn't always see the player is standing on the platform (important because the player can only jump while standing on something).
I've tried setting the player object's transform.translate, which prevents the player from moving left or right as long as it is touching the platform. I've also tried setting the player object's transform.parent to the platform's transform, but that "glues" the player in place to the platform, preventing even jumping. I've also tried searching for a solution/example, and there are plenty of examples for riding a left-right moving platform, but I haven't been able to get those examples to work for a falling platform.
Here is the script controlling the players left-right movement and jumping. This is attached to the player object:
public class Player : MonoBehaviour
{
public float jumpForce = 5;
public float horizontalSpeed = 0.1F;
public LayerMask whatIsGround;
private Rigidbody2D rb2d;
private Collider2D myCollider;
private bool grounded;
private float lastHorizontalInput;
void Start()
{
rb2d = GetComponent<Rigidbody2D>();
myCollider = GetComponent<Collider2D>();
}
void Update()
{
// If the player is trying to jump, only do so if the player is on a platform
grounded = Physics2D.IsTouchingLayers(myCollider, whatIsGround);
if (Input.GetKeyDown(KeyCode.Space) && grounded)
{
rb2d.velocity = new Vector2(rb2d.velocity.x, jumpForce);
}
MoveHorizonltally();
}
private void MoveHorizonltally()
{
float horizontalVelocity;
float horizontalInput = Input.GetAxis("Horizontal");
horizontalVelocity = GetHorizontalVelocity(horizontalInput);
if (horizontalVelocity != 0)
{
rb2d.position = new Vector2(rb2d.position.x + horizontalVelocity, rb2d.position.y);
}
}
private float GetHorizontalVelocity(float horizontalInput)
{
// Default to no horizontal motion
float result = 0;
bool leftPressed = Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.LeftArrow);
bool rightPressed = Input.GetKey(KeyCode.D) || Input.GetKey(KeyCode.RightArrow);
// Only a left key is being pressed; the player is going left
if (leftPressed && !rightPressed)
{
result = -1 * horizontalSpeed;
}
// Only a right key is being pressed; the player is going right
else if (rightPressed && !leftPressed)
{
result = horizontalSpeed;
}
// Both keys are being pressed
else if (leftPressed && rightPressed)
{
// The most recent key press gets priority; ignore the oldest key press
if (lastHorizontalInput < 0)
{
// Oldest key pressed is a left direction, so go right
result = horizontalSpeed;
}
else
{
// Oldest key pressed is a right direction, so go left
result = -1 * horizontalSpeed;
}
}
lastHorizontalInput = horizontalInput;
return result;
}
}
Here is the script responsible for making the platform fall. This is attached to the platform object:
public class PlatformFalling : MonoBehaviour
{
public float fallSpeed;
private GameObject player;
public void Start()
{
player = GameObject.FindGameObjectWithTag("Player");
}
// Update is called once per frame
void Update()
{
bool playerIsOnPlatform = player.GetComponent<Collider2D>().IsTouching(GetComponent<Collider2D>()); ;
Vector2 fallDistance = Vector2.down * fallSpeed;
transform.Translate(fallDistance);
if (playerIsOnPlatform)
{
player.transform.Translate(fallDistance);
}
}
}
I'm new to Unity and C#, trying to make a 2D game.
The animator controller screenshot with all the transition is attached, the (isGrounded) bool from idle to jump is false, from jump to idle is true, and from run to jump is false, but in this case, the character doesn't jump, it shakes in its place transitioning from idle to jump very quickly. When I remove the jump animation the character moves normally but of course no jumping. What could be the problem here?
This is also the CharacterController2D script:
public float jumpForce = 600f;
// player health
public int playerHealth = 1;
// LayerMask to determine what is considered ground for the player
public LayerMask whatIsGround;
internal void EnemyBounce(CharacterController2D characterController2D)
{
throw new NotImplementedException();
}
// Transform just below feet for checking if player is grounded
public Transform groundCheck;
// player can move?
// we want this public so other scripts can access it but we don't want to show in editor as it might confuse designer
[HideInInspector]
public bool playerCanMove = true;
// SFXs
public AudioClip coinSFX;
public AudioClip deathSFX;
public AudioClip fallSFX;
public AudioClip jumpSFX;
public AudioClip victorySFX;
// private variables below
// store references to components on the gameObject
Transform _transform;
Rigidbody2D _rigidbody;
Animator _animator;
AudioSource _audio;
// hold player motion in this timestep
float _vx;
float _vy;
// player tracking
bool _facingRight = true;
bool _isGrounded = false;
bool _isRunning = false;
bool _canDoubleJump = false;
// store the layer the player is on (setup in Awake)
int _playerLayer;
// number of layer that Platforms are on (setup in Awake)
int _platformLayer;
void Awake()
{
// get a reference to the components we are going to be changing and store a reference for efficiency purposes
_transform = GetComponent<Transform>();
_rigidbody = GetComponent<Rigidbody2D>();
if (_rigidbody == null) // if Rigidbody is missing
Debug.LogError("Rigidbody2D component missing from this gameobject");
_animator = GetComponent<Animator>();
if (_animator == null) // if Animator is missing
Debug.LogError("Animator component missing from this gameobject");
_audio = GetComponent<AudioSource>();
if (_audio == null)
{ // if AudioSource is missing
Debug.LogWarning("AudioSource component missing from this gameobject. Adding one.");
// let's just add the AudioSource component dynamically
_audio = gameObject.AddComponent<AudioSource>();
}
// determine the player's specified layer
_playerLayer = this.gameObject.layer;
// determine the platform's specified layer
_platformLayer = LayerMask.NameToLayer("Platform");
}
// this is where most of the player controller magic happens each game event loop
void Update()
{
// exit update if player cannot move or game is paused
if (!playerCanMove || (Time.timeScale == 0f))
return;
// determine horizontal velocity change based on the horizontal input
_vx = CrossPlatformInputManager.GetAxisRaw("Horizontal");
// Determine if running based on the horizontal movement
if (_vx != 0)
{
_isRunning = true;
}
else
{
_isRunning = false;
}
// set the running animation state
_animator.SetBool("Running", _isRunning);
// get the current vertical velocity from the rigidbody component
_vy = _rigidbody.velocity.y;
// Check to see if character is grounded by raycasting from the middle of the player
// down to the groundCheck position and see if collected with gameobjects on the
// whatIsGround layer
_isGrounded = Physics2D.Linecast(_transform.position, groundCheck.position, whatIsGround);
// allow double jump after grounded
if (_isGrounded)
{
_canDoubleJump = true;
}
// Set the grounded animation states
_animator.SetBool("Grounded", _isGrounded);
if (_isGrounded && CrossPlatformInputManager.GetButtonDown("Jump")) // If grounded AND jump button pressed, then allow the player to jump
{
DoJump();
}
else if (_canDoubleJump && CrossPlatformInputManager.GetButtonDown("Jump")) // If candoublejump and jump button pressed, then allow player to double jump
{
DoJump();
// disable double hump after double jumping since you can only really do it once
_canDoubleJump = false;
}
// If the player stops jumping mid jump and player is not yet falling
// then set the vertical velocity to 0 (he will start to fall from gravity)
if (CrossPlatformInputManager.GetButtonUp("Jump") && _vy > 0f)
{
_vy = 0f;
}
// Change the actual velocity on the rigidbody
_rigidbody.velocity = new Vector2(_vx * moveSpeed, _vy);
// if moving up then don't collide with platform layer
// this allows the player to jump up through things on the platform layer
// NOTE: requires the platforms to be on a layer named "Platform"
Physics2D.IgnoreLayerCollision(_playerLayer, _platformLayer, (_vy > 0.0f));
}
// Checking to see if the sprite should be flipped
// this is done in LateUpdate since the Animator may override the localScale
// this code will flip the player even if the animator is controlling scale
void LateUpdate()
{
// get the current scale
Vector3 localScale = _transform.localScale;
if (_vx > 0) // moving right so face right
{
_facingRight = true;
}
else if (_vx < 0)
{ // moving left so face left
_facingRight = false;
}
// check to see if scale x is right for the player
// if not, multiple by -1 which is an easy way to flip a sprite
if (((_facingRight) && (localScale.x < 0)) || ((!_facingRight) && (localScale.x > 0)))
{
localScale.x *= -1;
}
// update the scale
_transform.localScale = localScale;
}
// if the player collides with a MovingPlatform, then make it a child of that platform
// so it will go for a ride on the MovingPlatform
void OnCollisionEnter2D(Collision2D other)
{
if (other.gameObject.tag == "MovingPlatform")
{
this.transform.parent = other.transform;
}
}
// if the player exits a collision with a moving platform, then unchild it
void OnCollisionExit2D(Collision2D other)
{
if (other.gameObject.tag == "MovingPlatform")
{
this.transform.parent = null;
}
}
//make the player jump
void DoJump()
{
// reset current vertical motion to 0 prior to jump
_vy = 0f;
// add a force in the up direction
_rigidbody.AddForce(new Vector2(4, jumpForce));
// play the jump sound
PlaySound(jumpSFX);
}
// do what needs to be done to freeze the player
void FreezeMotion()
{
playerCanMove = false;
_rigidbody.velocity = new Vector2(0, 0);
_rigidbody.isKinematic = true;
}
// do what needs to be done to unfreeze the player
void UnFreezeMotion()
{
playerCanMove = true;
_rigidbody.isKinematic = false;
}
// play sound through the audiosource on the gameobject
void PlaySound(AudioClip clip)
{
_audio.PlayOneShot(clip);
}
// public function to apply damage to the player
public void ApplyDamage(int damage)
{
if (playerCanMove)
{
playerHealth -= damage;
if (playerHealth <= 0)
{ // player is now dead, so start dying
PlaySound(deathSFX);
StartCoroutine(KillPlayer());
}
}
}
// public function to kill the player when they have a fall death
public void FallDeath()
{
if (playerCanMove)
{
playerHealth = 0;
PlaySound(fallSFX);
StartCoroutine(KillPlayer());
}
}
// coroutine to kill the player
IEnumerator KillPlayer()
{
if (playerCanMove)
{
// freeze the player
FreezeMotion();
// play the death animation
_animator.SetTrigger("Death");
// After waiting tell the GameManager to reset the game
yield return new WaitForSeconds(2.0f);
if (GameManager.gm) // if the gameManager is available, tell it to reset the game
GameManager.gm.ResetGame();
else // otherwise, just reload the current level
SceneManager.LoadScene(SceneManager.GetActiveScene().name);
}
}
public void CollectCoin(int amount)
{
PlaySound(coinSFX);
if (GameManager.gm) // add the points through the game manager, if it is available
GameManager.gm.AddPoints(amount);
}
// public function on victory over the level
public void Victory()
{
PlaySound(victorySFX);
FreezeMotion();
_animator.SetTrigger("Victory");
if (GameManager.gm) // do the game manager level compete stuff, if it is available
GameManager.gm.LevelCompete();
}
// public function to respawn the player at the appropriate location
public void Respawn(Vector3 spawnloc)
{
UnFreezeMotion();
playerHealth = 1;
_transform.parent = null;
_transform.position = spawnloc;
_animator.SetTrigger("Respawn");
}
public void EnemyBounce()
{
DoJump();
}
}
I also tried adding a separate Jump script, it doesn't work.
Just gonna take some notes while reading the code...
This:
// Determine if running based on the horizontal movement
if (_vx != 0)
{
_isRunning = true;
}
else
{
_isRunning = false;
}
// set the running animation state
_animator.SetBool("Running", _isRunning);
Can be replaced by
_isRunning = _vx != 0;
_animator.SetBool("Running", _isRunning);
or even just creating a property accessor
bool _isRunning {
get {
return _vx != 0;
}
}
As for your actual question; I can't see your transitions but I'm assuming there's something wrong with them, keep trying to debug it by removing SetBools, and check the Animator on what is being triggered. The Any State -> Idle looks suspicious.
I am trying to deploy the Unity Survival Shooter game to the android device. The game works just fine except when I shoot the enemy, it doesn't take any damage and don't die.
Here is my PlayerShooting script.
using UnityEngine;
using System.Threading;
using UnityStandardAssets.CrossPlatformInput;
namespace CompleteProject
{
public class PlayerShooting : MonoBehaviour
{
public int damagePerShot = 20; // The damage inflicted by each bullet.
public float timeBetweenBullets = 0.15f; // The time between each shot.
public float range = 100f; // The distance the gun can fire.
float timer; // A timer to determine when to fire.
Ray shootRay; // A ray from the gun end forwards.
RaycastHit shootHit; // A raycast hit to get information about what was hit.
int shootableMask; // A layer mask so the raycast only hits things on the shootable layer.
ParticleSystem gunParticles; // Reference to the particle system.
LineRenderer gunLine; // Reference to the line renderer.
AudioSource gunAudio; // Reference to the audio source.
Light gunLight; // Reference to the light component.
public Light faceLight; // Duh
float effectsDisplayTime = 0.2f; // The proportion of the timeBetweenBullets that the effects will display for.
public float timertime = 0.0f;
void Awake ()
{
// Create a layer mask for the Shootable layer.
shootableMask = LayerMask.GetMask ("Shootable");
// Set up the references.
gunParticles = GetComponent<ParticleSystem> ();
gunLine = GetComponent <LineRenderer> ();
gunAudio = GetComponent<AudioSource> ();
gunLight = GetComponent<Light> ();
//faceLight = GetComponentInChildren<Light> ();
}
void Update ()
{
// Add the time since Update was last called to the timer.
timer += Time.deltaTime;
#if !MOBILE_INPUT
// If the Fire1 button is being press and it's time to fire...
if(Input.GetButton ("Fire1") && timer >= timeBetweenBullets && Time.timeScale != 0)
{
// ... shoot the gun.
Shoot ();
}
#else
// If there is input on the shoot direction stick and it's time to fire.
bool check = CrossPlatformInputManager.GetButtonDown("JumpButton");
check = true;
//Debug.Log(check);
if(check == true)
// if ((CrossPlatformInputManager.GetAxisRaw("Move X") != 0 || CrossPlatformInputManager.GetAxisRaw("Move Y") != 0) && timer >= timeBetweenBullets)
{
// ... shoot the gun
//System.Threading.Thread.Sleep(2000);
timertime -= Time.deltaTime;
if(timertime < 0.0f)
{
Shoot();
timertime = 0.175f;
}
}
#endif
// If the timer has exceeded the proportion of timeBetweenBullets that the effects should be displayed for...
if(timer >= timeBetweenBullets * effectsDisplayTime)
{
// ... disable the effects.
DisableEffects ();
}
}
public void DisableEffects ()
{
// Disable the line renderer and the light.
gunLine.enabled = false;
faceLight.enabled = false;
gunLight.enabled = false;
}
public void Shoot ()
{
// Reset the timer.
Debug.Log("Inside Shoot");
timer = 0f;
// Play the gun shot audioclip.
gunAudio.Play ();
// Enable the lights.
gunLight.enabled = true;
faceLight.enabled = true;
// Stop the particles from playing if they were, then start the particles.
gunParticles.Stop ();
gunParticles.Play ();
// Enable the line renderer and set it's first position to be the end of the gun.
gunLine.enabled = true;
gunLine.SetPosition (0, transform.position);
// Set the shootRay so that it starts at the end of the gun and points forward from the barrel.
shootRay.origin = transform.position;
shootRay.direction = transform.forward;
// Perform the raycast against gameobjects on the shootable layer and if it hits something...
Debug.Log("Going inside Physics Raycast");
if(Physics.Raycast (shootRay, out shootHit, range, shootableMask))
{
// Try and find an EnemyHealth script on the gameobject hit.
Debug.Log("Inside Physics Raycast");
EnemyHealth enemyHealth = shootHit.collider.GetComponent <EnemyHealth> ();
Debug.Log (enemyHealth);
Debug.Log ("Checking if enemyHealth is not null");
// If the EnemyHealth component exist...
if(enemyHealth != null)
{
// ... the enemy should take damage.
Debug.Log("Inside enemyHealth != null if condition");
enemyHealth.TakeDamage (damagePerShot, shootHit.point);
}
// Set the second position of the line renderer to the point the raycast hit.
gunLine.SetPosition (1, shootHit.point);
}
// If the raycast didn't hit anything on the shootable layer...
else
{
// ... set the second position of the line renderer to the fullest extent of the gun's range.
gunLine.SetPosition (1, shootRay.origin + shootRay.direction * range);
}
}
}
}
And here is my EnemyHealth script.
using UnityEngine;
using UnityStandardAssets.CrossPlatformInput;
namespace CompleteProject
{
public class EnemyHealth : MonoBehaviour
{
public int startingHealth = 100; // The amount of health the enemy starts the game with.
public int currentHealth; // The current health the enemy has.
public float sinkSpeed = 2.5f; // The speed at which the enemy sinks through the floor when dead.
public int scoreValue = 10; // The amount added to the player's score when the enemy dies.
public AudioClip deathClip; // The sound to play when the enemy dies.
Animator anim; // Reference to the animator.
AudioSource enemyAudio; // Reference to the audio source.
ParticleSystem hitParticles; // Reference to the particle system that plays when the enemy is damaged.
CapsuleCollider capsuleCollider; // Reference to the capsule collider.
bool isDead; // Whether the enemy is dead.
bool isSinking; // Whether the enemy has started sinking through the floor.
void Awake ()
{
// Setting up the references.
anim = GetComponent <Animator> ();
enemyAudio = GetComponent <AudioSource> ();
hitParticles = GetComponentInChildren <ParticleSystem> ();
capsuleCollider = GetComponent <CapsuleCollider> ();
// Setting the current health when the enemy first spawns.
currentHealth = startingHealth;
}
void Update ()
{
// If the enemy should be sinking...
if(isSinking)
{
// ... move the enemy down by the sinkSpeed per second.
transform.Translate (-Vector3.up * sinkSpeed * Time.deltaTime);
}
}
public void TakeDamage (int amount, Vector3 hitPoint)
{
// If the enemy is dead...
if(isDead)
// ... no need to take damage so exit the function.
return;
// Play the hurt sound effect.
enemyAudio.Play ();
// Reduce the current health by the amount of damage sustained.
currentHealth -= amount;
// Set the position of the particle system to where the hit was sustained.
hitParticles.transform.position = hitPoint;
// And play the particles.
hitParticles.Play();
// If the current health is less than or equal to zero...
if(currentHealth <= 0)
{
// ... the enemy is dead.
Death ();
}
}
void Death ()
{
// The enemy is dead.
isDead = true;
// Turn the collider into a trigger so shots can pass through it.
capsuleCollider.isTrigger = true;
// Tell the animator that the enemy is dead.
anim.SetTrigger ("Dead");
// Change the audio clip of the audio source to the death clip and play it (this will stop the hurt clip playing).
enemyAudio.clip = deathClip;
enemyAudio.Play ();
}
public void StartSinking ()
{
// Find and disable the Nav Mesh Agent.
GetComponent <UnityEngine.AI.NavMeshAgent> ().enabled = false;
// Find the rigidbody component and make it kinematic (since we use Translate to sink the enemy).
GetComponent <Rigidbody> ().isKinematic = true;
// The enemy should no sink.
isSinking = true;
// Increase the score by the enemy's score value.
ScoreManager.score += scoreValue;
// After 2 seconds destory the enemy.
Destroy (gameObject, 2f);
}
}
}
I have put the log everywhere and found that the enemyHealth object from PlayerShooting script is always returning Null even though if I hit the enemy with bullets.
Need to know why it is always returning Null and how do I make it other than Null when I hit the enemy.
You are already using Layer to make sure that the raycast hit just the GameObjects on the shootableMask layer which is the "Shootable" layer so layer issue problem is eliminated.
The only possible problem left is that the EnemyHealth script is not attached to the GameObject or maybe some of the GameObjects.
Go through all your GameObjects and prefabs, select each one on the "Shootable" layer then make sure that the EnemyHealth script is attached to them. The GetComponent <EnemyHealth>() should never be null if the EnemyHealth script is attached to each one.
You should change the Getcomponent<> function into FindObjectOfType because Getcomponent only gets the component from that game object, in this situation the EnemyHealth Script doesn't exist in same object with PlayerShooting so you cant get the component. Read more about FindObjectOfType
I am using the standard 2d assets to learn developing 2d game with Unity, and I place a sprite with box-collider-2d, and choose the default standard assets CharacterRobotBoy to mess around with.
But I find that if I jumped and it's highly likely that the character will jump into the sprite which was intended to be made as a ground, but this will not happen every time. hope could get some help with that.
find the problem hard to describe and upload a video on youtue
EDIT
will just paste the script from the demo asset as required.
File PlatformerCharacter2D.cs
using System;
using UnityEngine;
namespace UnityStandardAssets._2D
{
public class PlatformerCharacter2D : MonoBehaviour
{
[SerializeField] private float m_MaxSpeed = 10f; // The fastest the player can travel in the x axis.
[SerializeField] private float m_JumpForce = 400f; // Amount of force added when the player jumps.
[Range(0, 1)] [SerializeField] private float m_CrouchSpeed = .36f; // Amount of maxSpeed applied to crouching movement. 1 = 100%
[SerializeField] private bool m_AirControl = false; // Whether or not a player can steer while jumping;
[SerializeField] private LayerMask m_WhatIsGround; // A mask determining what is ground to the character
private Transform m_GroundCheck; // A position marking where to check if the player is grounded.
const float k_GroundedRadius = .2f; // Radius of the overlap circle to determine if grounded
private bool m_Grounded; // Whether or not the player is grounded.
private Transform m_CeilingCheck; // A position marking where to check for ceilings
const float k_CeilingRadius = .01f; // Radius of the overlap circle to determine if the player can stand up
private Animator m_Anim; // Reference to the player's animator component.
private Rigidbody2D m_Rigidbody2D;
private bool m_FacingRight = true; // For determining which way the player is currently facing.
private void Awake()
{
// Setting up references.
m_GroundCheck = transform.Find("GroundCheck");
m_CeilingCheck = transform.Find("CeilingCheck");
m_Anim = GetComponent<Animator>();
m_Rigidbody2D = GetComponent<Rigidbody2D>();
}
private void FixedUpdate()
{
m_Grounded = false;
// The player is grounded if a circlecast to the groundcheck position hits anything designated as ground
// This can be done using layers instead but Sample Assets will not overwrite your project settings.
Collider2D[] colliders = Physics2D.OverlapCircleAll(m_GroundCheck.position, k_GroundedRadius, m_WhatIsGround);
for (int i = 0; i < colliders.Length; i++)
{
if (colliders[i].gameObject != gameObject)
m_Grounded = true;
}
m_Anim.SetBool("Ground", m_Grounded);
// Set the vertical animation
m_Anim.SetFloat("vSpeed", m_Rigidbody2D.velocity.y);
}
public void Move(float move, bool crouch, bool jump)
{
// If crouching, check to see if the character can stand up
if (!crouch && m_Anim.GetBool("Crouch"))
{
// If the character has a ceiling preventing them from standing up, keep them crouching
if (Physics2D.OverlapCircle(m_CeilingCheck.position, k_CeilingRadius, m_WhatIsGround))
{
crouch = true;
}
}
// Set whether or not the character is crouching in the animator
m_Anim.SetBool("Crouch", crouch);
//only control the player if grounded or airControl is turned on
if (m_Grounded || m_AirControl)
{
// Reduce the speed if crouching by the crouchSpeed multiplier
move = (crouch ? move*m_CrouchSpeed : move);
// The Speed animator parameter is set to the absolute value of the horizontal input.
m_Anim.SetFloat("Speed", Mathf.Abs(move));
// Move the character
m_Rigidbody2D.velocity = new Vector2(move*m_MaxSpeed, m_Rigidbody2D.velocity.y);
// If the input is moving the player right and the player is facing left...
if (move > 0 && !m_FacingRight)
{
// ... flip the player.
Flip();
}
// Otherwise if the input is moving the player left and the player is facing right...
else if (move < 0 && m_FacingRight)
{
// ... flip the player.
Flip();
}
}
// If the player should jump...
if (m_Grounded && jump && m_Anim.GetBool("Ground"))
{
// Add a vertical force to the player.
m_Grounded = false;
m_Anim.SetBool("Ground", false);
m_Rigidbody2D.AddForce(new Vector2(0f, m_JumpForce));
}
}
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;
}
}
}
Script Platformer2DUserControl.cs
using System;
using UnityEngine;
using UnityStandardAssets.CrossPlatformInput;
namespace UnityStandardAssets._2D
{
[RequireComponent(typeof (PlatformerCharacter2D))]
public class Platformer2DUserControl : MonoBehaviour
{
private PlatformerCharacter2D m_Character;
private bool m_Jump;
private void Awake()
{
m_Character = GetComponent<PlatformerCharacter2D>();
}
private void Update()
{
if (!m_Jump)
{
// Read the jump input in Update so button presses aren't missed.
m_Jump = CrossPlatformInputManager.GetButtonDown("Jump");
}
}
private void FixedUpdate()
{
// Read the inputs.
bool crouch = Input.GetKey(KeyCode.LeftControl);
float h = CrossPlatformInputManager.GetAxis("Horizontal");
// Pass all parameters to the character control script.
m_Character.Move(h, crouch, m_Jump);
m_Jump = false;
}
}
}