How to stop movement and/or rotation of a Unity gameObject - c#

I am making a small game that is based on the Roll-A-Ball tutorial from Unity, though I haven't used the actual tutorial. I incorporated a respawn mechanic, but if you are moving around when you die, then after you respawn, you still have that momentum after you land. I have tried to fix this, but I am not sure how since I am still pretty new at using Unity. I have a video that shows this: https://drive.google.com/open?id=1752bPBDVOe2emN_hmnlPaD4uaJQITpsP
Here is the C# script that handles respawn:
public class PlayerBehavior : MonoBehaviour
{
Rigidbody PlayerRB;
public bool Dead;
private int timer;
public GameObject Particles;
public bool InRespawn;
void Update()
{
PlayerRB = GetComponent<Rigidbody>();
if (Dead)
{
StartCoroutine("Respawn");
}
}
IEnumerator Respawn()
{
InRespawn = true; //Used to prevent movement during respawn.
PlayerRB.useGravity = false;
transform.position = new Vector3(0, 4, 0);
transform.rotation = new Quaternion(-80, 0, 0, 0); // Resets position.
Dead = false;
Instantiate(Particles, transform); // Adds respawn particle effect.
yield return new WaitForSeconds(2);
Destroy(this.gameObject.transform.GetChild(0).gameObject);
PlayerRB.useGravity = true;
PlayerRB.AddForce(0, 400, 0); // Does a little hop.
InRespawn = false; // Tells the game that respawn is finished.
}
}

Zero out the rigidbody's velocity when the respawn occurs:
IEnumerator Respawn()
{
PlayerRB.velocity = Vector3.zero;
// ... rest of method
}
As a sidenote, you probably don't need to run GetComponent on every frame. It's an expensive operation so it's best to do it as infrequently as you can get away with:
void Start()
{
PlayerRB = GetComponent<Rigidbody>();
}
void Update()
{
if (Dead)
{
StartCoroutine("Respawn");
}
}
If instead you would like to disable all physics interactions with the player while it is dead, you can set it to be kinematic during that time. Just be sure to unset isKinematic before adding force to it.
IEnumerator Respawn()
{
PlayerRB.isKinematic = true;
// ... rest of method
PlayerRB.isKinematic = false;
PlayerRB.useGravity = true;
PlayerRB.AddForce(0, 400, 0); // Does a little hop.
InRespawn = false; // Tells the game that respawn is finished.
}

make a bool in your code like this
bool isDead=false;
then make it true when you die
the add this into you update
if(isDead){
rb.velocity=vector3.zero;
}
this will stop you objects movements if it is dead

Related

Why sometimes the player is making a circle movement around the target?

The main goal of the script in this case is when the player is getting too close to the fire to slowly stop walking automatic wait some seconds then automatic rotate and start walking again and then stop again slowly.
The script is working when the player is entering the collider area this is the target variable position so the player is rotating back to where he was entered from.
The idea is to make something nice to prevent from the player to get into the fire. but i'm facing two problems.
The first problem is that in the script i'm using a box collider as the area to prevent from the player to get closer to the fire and it's hard to dynamic change the collider area shape to cover all sides.
This is a screenshot of the collider area :
I marked to possible places if the player is coming from closer to the fire when he enter/exit the collider area he is already inside the fire and it's hard to change the collider size and scale to cover this places too.
I wonder if using distance check instead of the box collider will be easier ? and if it is how to change the script to use distance check instead the box collider trigger enter and exit events ?
The second problem is that sometimes when the player got close to the fire and then rotating back outside the collider area when he exit at that point(position) the player is making a walking circle around the target position and then continue outside. not sure why the player is making sometimes a moving around the target point ?
The script is attached to the player :
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityStandardAssets.Characters.ThirdPerson;
public class SpreadedFireDistanceCheck : MonoBehaviour
{
public Vector3 target;
public float rotationSpeed;
public GameObject descriptionTextImage;
public TextMeshProUGUI text;
public Transform player;
private Animator anim;
private ThirdPersonUserControl thirdPersonUserControl;
private bool startRotBack = false;
private bool rot = false;
private bool doOnce = true;
private bool getTargetPos = false;
float angle = 10;
// Start is called before the first frame update
void Start()
{
anim = player.GetComponent<Animator>();
thirdPersonUserControl = player.GetComponent<ThirdPersonUserControl>();
}
// Update is called once per frame
void Update()
{
if (startRotBack)
{
if (doOnce)
{
anim.SetTrigger("Idle Exit");
StartCoroutine(WaitTime());
doOnce = false;
}
if (rot)
{
anim.SetBool("Walk", true);
if (Vector3.Angle(player.transform.forward, target - player.transform.position) > angle)
{
Vector3 dir = target - player.transform.position;
Quaternion lookRotation = Quaternion.LookRotation(dir);
Vector3 rotation = Quaternion.Lerp(player.transform.rotation, lookRotation, Time.deltaTime * rotationSpeed).eulerAngles;
player.transform.rotation = Quaternion.Euler(0f, rotation.y, 0f);
}
}
}
}
private void OnTriggerExit(Collider other)
{
if (other.name == "kid_from_space")
{
if (rot)
{
rot = false;
anim.SetBool("Walk", false);
anim.SetTrigger("Idle Enter");
thirdPersonUserControl.enabled = true;
getTargetPos = false;
}
}
}
private void OnTriggerEnter(Collider other)
{
if (other.name == "kid_from_space")
{
if (getTargetPos == false)
{
target = player.transform.position;
getTargetPos = true;
}
descriptionTextImage.SetActive(true);
text.text = "This flames are so hot, i better stay away.";
thirdPersonUserControl.enabled = false;
doOnce = true;
startRotBack = true;
}
}
private IEnumerator WaitTime()
{
yield return new WaitForSeconds(5f);
text.text = "";
descriptionTextImage.SetActive(false);
rot = true;
}
}
In general the script is working but this two problem i mentioned above is hard to solve.
The player have this components :
Animator , Rigidbody , Capsule Collider , Third Person User Control (Script) , Third Person Character (Script)

Enemy shooting bullets every 5 seconds in unity 3d

I have a problem, I am trying to make the enemy shoot at the player every 5 seconds and right now it is just shooting lots of bullets constantly in a line.
This is my code, I would really appreciate some help!
void ShootAtPlayer()
{
StartCoroutine(bulletshooting());
IEnumerator bulletshooting()
{
shooting = true;
if (shooting == true)
{
GameObject tempBullet = Instantiate(enemyBullet, eyes.gameObject.transform.position, eyes.gameObject.transform.rotation) as GameObject; //shoots from enemies eyes
Rigidbody tempRigidBodyBullet = tempBullet.GetComponent<Rigidbody>();
tempRigidBodyBullet.AddForce(tempRigidBodyBullet.transform.forward * enemyBulletSpeed);
Destroy(tempBullet, 0.1f);
yield return new WaitForSeconds(5f);
}
shooting = false;
}
From your comment
shootAtPlayer is called in the update when the enemy is close enough to the player
The issue is: You are starting a new Coroutine every frame!
In your case I wouldn't use a Coroutine at all since you already have a code that is executed every frame. (Because otherwise you would need some code to also stop the running routine)
Rather use a simple timer:
[SerializeField] private float cooldown = 5;
private float cooldownTimer;
void ShootAtPlayer()
{
cooldownTimer -= Time.deltaTime;
if(cooldownTimer > 0) return;
cooldownTimer = cooldown;
GameObject tempBullet = Instantiate(enemyBullet, eyes.gameObject.transform.position, eyes.gameObject.transform.rotation) as GameObject; //shoots from enemies eyes
Rigidbody tempRigidBodyBullet = tempBullet.GetComponent<Rigidbody>();
tempRigidBodyBullet.AddForce(tempRigidBodyBullet.transform.forward * enemyBulletSpeed);
Destroy(tempBullet, 0.1f);
}
If you really want to use a Coroutine for that it would probably look like
private bool isShooting;
void ShootAtPlayer()
{
// Only allow a new routine if there is none running already
if(isShooting) return;
StartCoroutine (shootRoutine());
}
private IEnumerator shootRoutine()
{
// Just in case avoid concurrent routines
if(isShooting) yield break;
isShooting = true;
GameObject tempBullet = Instantiate(enemyBullet, eyes.gameObject.transform.position, eyes.gameObject.transform.rotation) as GameObject; //shoots from enemies eyes
Rigidbody tempRigidBodyBullet = tempBullet.GetComponent<Rigidbody>();
tempRigidBodyBullet.AddForce(tempRigidBodyBullet.transform.forward * enemyBulletSpeed);
Destroy(tempBullet, 0.1f);
yield return new WaitForSeconds (5f);
isShooting = false;
}

Unity 3D, how to spawn objects, and modify their values?

i try to make a simple 3D Rail Shooter, and i currently stuck on how to spawn the bullets for my Ship.
I want when i press on fire that the bullet gets spawned and gets shooted.
I created an empty gameObject as a child of my ship and put a script on it.
The problem is i currently stuck and i can't figure out how to get it done.
So im asking for help, what did i miss, what did i wrong?
Here is the script i came up with:
public Rigidbody rb;
private bool isMoving = false;
private bool isFirePressed = false;
void Start()
{
rb = GetComponent<Rigidbody>();
rb.useGravity = false;
}
void Update()
{
isFirePressed = Input.GetButtonDown("Fire1");
}
void FixedUpdate()
{
if (Input.GetButtonDown("Fire1"))
{
// the cube is going to move upwards in 10 units per second
rb.velocity = new Vector3(0, 0, 100);
isMoving = true;
Debug.Log("fire");
}
}
First I guess you wanted to use your variable isFirePressed.
Then if that is a prefab I guess you rather want to Instantiate a new bullet:
if (isFirePressed)
{
var newBullet = Instantiate (rb, transform);
// the cube is going to move upwards in 10 units per second
newBullet.velocity = new Vector3(0, 0, 100);
newBullet.useGravity = false;
isMoving = true;
Debug.Log("fire");
}
You changed the velocity on the prefab which doesn't work.
Additionally note that the velocity is in World-Space coordinates. So currently you are shooting in world Z direction no matter where your plane is facing to.
I would rather use e.g.
newBullet.velocity = transform.forward * 100;
to shoot it in the direction your BulletEmitter is facing towards.

2D Character not jumping issue in Unity

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.

Unity Standard assets Cross Platform input not working

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();
}
}
}

Categories

Resources