Player stuck on reactivation - not changing position to spawn - c#

I'm writing a script controlling the enter and exit of a space ship in a 2D game.
The problem I'm running into is when exiting the ship, the player is reactivated, and you regain control, but it does not move the player to the empty gameobject I have attached to the ship, in a beginners attempt to move the player to the location of the ship, without ever destroying the player. The player simply spawns on its last known location prior to entering the ship, and I seem to be forced into that location, I can try to move, but its like I'm anchored to that position.
using UnityEngine;
using System.Collections;
public class SpaceShipActivator : MonoBehaviour
{
//Takeoff
public bool inRange;
public SpaceShipAtmosphereController SpaceShipAtmosphereController;
public PlayerController playerControl;
public GameObject Player;
public bool onBoard;
//End Takeoff
//Landing
public Transform Spawn;
public Transform landingGear2;
public Transform landingGear;
public LayerMask whatIsGround;
float groundRadius = 0.2f;
bool getIn;
bool landingGearStable;
bool landingGearStable2;
bool shipStable;
//EndLanding
Animator anim;
void Start()
{
anim = GetComponent<Animator>();
inRange = false;
SpaceShipAtmosphereController.enabled = false;
}
void Update()
{
AnimationUpdate();
//Launch
if (inRange && Input.GetButtonDown("Interact") && !onBoard)
{
LaunchShip();
}
//End launch
CheckLandingGear();
//Land
if(onBoard && Input.GetButtonDown("Roll"))
{
LandShip();
}
//End Land
}
//*********************************Functions**************************************
void LaunchShip()
{
anim.SetBool("Get In", true);
this.gameObject.tag = "Player";
SpaceShipAtmosphereController.enabled = true;
Player.tag = "InactivePlayer";
playerControl.enabled = false;
Player.SetActive(false);
onBoard = true;
}
void LandShip()
{
anim.SetBool("Get Out", true);
this.gameObject.tag = "InactivePlayer";
Player.tag = "Player";
playerControl.enabled = true;
SpaceShipAtmosphereController.enabled = false;
onBoard = false;
Player.SetActive(true);
Player.transform.position = Spawn.transform.position;
}
void CheckLandingGear()
{
//landingGear
landingGearStable = Physics2D.OverlapCircle(landingGear.position, groundRadius, whatIsGround);
landingGearStable2 = Physics2D.OverlapCircle(landingGear2.position, groundRadius, whatIsGround);
if (landingGearStable && landingGearStable2)
{
shipStable = true;
}
//End landingGear
}
void AnimationUpdate()
{
anim.SetBool("Get In", false);
anim.SetBool("Get Out", false);
}
//For launching ship
//IF player: inRange enter/exit boolean control.
void OnTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("Player"))
{
//Debug.Log("houi p;gberf");
inRange = true;
}
}
void OnTriggerExit2D(Collider2D other)
{
if (other.CompareTag("Player"))
{
inRange = false;
}
}
//End IF player: inRange enter/exit boolean control.
}
On a side note, In that same script I've included landingGear, which is set to be two empty gameobjects that basically share Y and are spaced apart on X to check that the spaceship is not only grounded but level for the most part, so the animation doesn't look silly AND to check if the player can even get out. I know this isn't the question, but any input on it would be appreciated, but please don't feel obligated.
Thanks for the help

Related

Show and hide animation for a hand

So . I work at a 2d game in unity and I have some problems with some mechanics and i really need some help from you guys. All I want to do is to make my character hand to stop and grab a object. When I press E the animation of the hand start and have a collider for each frame, in case that the hand collide with a closer object, the animation to stop at that frame. I have a week since I try to figure it out. If you want to help me we can do it on discord. I will put the codes here, maybe the reason that I can't to what I want to do is very clear and I dont see it.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class showHide : MonoBehaviour
{
[SerializeField]
GameObject hand;
private Animator freeze;
public bool touch = false;
private bool ok = true;
// Start is called before the first frame update
void Start()
{
freeze = GetComponent<Animator>();
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.E) && ok == true)
{
freeze.Play("Follower");
StartCoroutine(show());
}
}
void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.tag == "box")
{
StartCoroutine(colliderShow());
}
}
private IEnumerator show()
{
ok = false;
hand.SetActive(true);
yield return new WaitForSeconds(4f);
hand.SetActive(false);
ok = true;
}
private IEnumerator colliderShow()
{
touch = true;
print(touch);
yield return new WaitForSeconds(4f);
touch = false;
print(touch);
}
private void FreezeAniamtion()
{
freeze.speed = 0f;
StartCoroutine(waitTime());
}
private IEnumerator waitTime()
{
yield return new WaitForSeconds(0f);
freeze.speed = 1f;
}
}
This is the code that activate and deactivate my hand object , including the animation .
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class facingScript : MonoBehaviour
{
private SpriteRenderer render;
private Camera mainCam;
private Vector3 mousePos;
private Animator aniHand;
public bool atinge;
void Start()
{
mainCam = Camera.main;
render = GetComponent<SpriteRenderer>();
aniHand = GetComponent<Animator>();
gameObject.SetActive(false);
}
// Update is called once per frame
void Update()
{
mousePos = Input.mousePosition;
mousePos = mainCam.ScreenToWorldPoint(
new Vector3(mousePos.x, mousePos.y, mainCam.transform.position.z - transform.position.z)
);
Vector3 rotation = mousePos - transform.position;
if (rotation.x > 0)
render.flipY = true;
else
render.flipY = false;
if (atinge == false)
aniHand.speed = 1f;
Debug.Log(aniHand.speed);
}
// Collision with objects
void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.tag == "box")
{
atinge = true;
aniHand.speed = 0f;
StartCoroutine(freezingTime());
}
}
private IEnumerator freezingTime()
{
yield return new WaitForSeconds(4f);
atinge = false;
}
// No collision with any object
private void FreezeAnimation()
{
aniHand.speed = 0f;
StartCoroutine(waitTime());
}
private IEnumerator waitTime()
{
yield return new WaitForSeconds(0f);
aniHand.speed = 1f;
}
}
This is the hand component script . When the hand don't collide with anything the object is deactivated . The FreezeAnimation() is a event at the last frame. I tryed to do a collider animation for the showHide component that will be exact with the hand animation collider for each frame to check if the hand collide in the showHide script and if it collide to have a 4 seconds of waiting with the hand at that position.
I really tryed my best but I really can't figure it out.

I am working in Unity and my Punch and jump animations don't play fully. How can I fix my code?

I am trying to get my character to punch and jump. Jump works but the animation does not always play. Punch will either not play at all or it will freeze halfway through the animation. Here is my code below. I think the error is in the lines surrounding the StopPunch (I did not write those but found in another solution to a similar question). Is the code right and my error is in unity possibly? Any help would be greatly appreciated!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class playermovement : MonoBehaviour {
public CharacterController2D controller;
public Animator animator;
public float runSpeed = 40f;
float horizontalMove = 0f;
bool jump = false;
bool crouch = false;
bool punch = false;
void Update()
{
horizontalMove = Input.GetAxisRaw("Horizontal") * runSpeed;
animator.SetFloat("Speed", Mathf.Abs(horizontalMove));
if (Input.GetButtonDown("Jump"))
{
jump = true;
animator.SetBool("IsJumping", true);
}
if (Input.GetButtonDown("Crouch"))
{
crouch = true;
}else if (Input.GetButtonUp("Crouch"))
{
crouch = false;
}
if (Input.GetButtonDown("Punch"))
{
punch = true;
if (punch)
{
animator.SetBool("IsPunching", true);
StartCoroutine(StopPunch(2.0));
}
}
void StopPunch (float waitTime)
{
yield WaitForSeconds (waitTime);
animator.SetBool("IsPunching", false);
}
}
public void OnLanding ()
{
animator.SetBool("IsJumping", false);
}
public void OnCrouching (bool isCrouching)
{
animator.SetBool("IsCrouching", isCrouching);
}
void FixedUpdate ()
{
// Move our character
controller.Move(horizontalMove * Time.fixedDeltaTime, crouch, jump);
jump = false;
animator.SetBool("IsPunching", false);
}
}
If you click on the transition away from punching, in the inspector you should see settings as in the screenshot which should allow for animations completing.
I'm guessing you'll need to play with some of these settings.

Everything breaks after using PlayOneShot

In a game I am working on, the player uses a cube to open doors. When the player interacts with the cube while near the door, the door slides open. I am now trying to make it so that while it slides open, it makes a sound as doors should but I kinda ran into some issues. When I tried to add in the sound for the door, it ignored the part where the door should open altogether.
Here is what I did:
I added an AudioSource to the Cube's child object, CORE because the Cube object already contains an AudioSource which will play at the same time as this sound and assigned it in my Cube's script...
public AudioSource Woosh;
void Start()
{
//Debug.Log("Script initialized!");
Hm = gameObject.GetComponent<AudioSource>();
anim = GameObject.Find("TheFirstDoor").GetComponent<Animator>();
//Door = GameObject.Find("TheFirstDoor").GetComponent<AudioSource>();
Woosh = GameObject.Find("CORE").GetComponent<AudioSource>();
}
Here's the interactive part of the script, it runs a check but for some reason, it is pretending CanBeKey is false...
public void OnActivate()
{
if(HasPlayed == false) //Have I played? Has the Time out passed?
{
HasPlayedFirstTime = true;
Hm.Play();
HasPlayed = true;
PlayTimeOut = 30.0f;
if(CanBeKey == true)
{
anim.Play("Door_Open");
//Door.Play();
StartCoroutine(PlayDaWoosh());
Debug.Log("OPENING!");
}
}
}
Now here is the IEnumerator part of the script, PlayDaWoosh()
IEnumerator PlayDaWoosh()
{
Woosh.PlayOneShot(Woosh.clip);
yield return new WaitForSeconds(Woosh.clip.length);
}
I am aware that the last code snippet is a bit messy but it was the best thing I can think of.
Here is the full script in case you are that curious.....
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CUBE_CORE : MonoBehaviour
{
public AudioSource Hm; // HM!!!
private bool HasPlayed = false;
public float PlayTimeOut = 0.0f;
public static bool CanBeKey = false;
public Animator anim;
public static bool HasPlayedFirstTime = false;
public static AudioSource Door;
public AudioSource Woosh;
// Start is called before the first frame update
void Start()
{
//Debug.Log("Script initialized!");
Hm = gameObject.GetComponent<AudioSource>();
anim = GameObject.Find("TheFirstDoor").GetComponent<Animator>();
//Door = GameObject.Find("TheFirstDoor").GetComponent<AudioSource>();
Woosh = GameObject.Find("CORE").GetComponent<AudioSource>();
}
// Update is called once per frame
void Update()
{
if(HasPlayed == true)
{
if (PlayTimeOut < 0.0f)
{
HasPlayed = false;
}
PlayTimeOut -= Time.smoothDeltaTime;
}
}
public void OnActivate()
{
if(HasPlayed == false) //Have I played? Has the Time out passed?
{
HasPlayedFirstTime = true;
Hm.Play();
HasPlayed = true;
PlayTimeOut = 30.0f;
if(CanBeKey == true)
{
anim.Play("Door_Open");
//Door.Play();
StartCoroutine(PlayDaWoosh());
Debug.Log("OPENING!");
}
}
}
private void OnTriggerEnter(Collider other)
{
if(other.gameObject.name == "SecondDoor")
{
anim = GameObject.Find("DoorSecond").GetComponent<Animator>();
}
if(other.gameObject.name == "ThirdDoor")
{
anim = GameObject.Find("TheThirdDoor").GetComponent<Animator>();
}
if(other.gameObject.name == "FourthDoor")
{
anim = GameObject.Find("TheFourthDoor").GetComponent<Animator>();
}
}
IEnumerator PlayDaWoosh()
{
Woosh.PlayOneShot(Woosh.clip);
yield return new WaitForSeconds(Woosh.clip.length);
}
}
Expected result: Door opening and sound playing
Actual result: Neither happening unless I remove anything that has to do with the Woosh
I apologize ahead of time if I wasn't specific enough or if the question was answered somewhere else. I am relatively new here.

OnTriggerEnter not working properly

In the game I'm making in order to call a dead state I'm using a box collider to track if the player enters in a particular zone, but the problem is that it only tracks it if I'm pressing any of the a,s,d or w keys in the keyboard.
This is the code.
The OnTriggerEnter is called in line 48.
using UnityEngine;
using System.Collections;
public class PlayerManager : MonoBehaviour
{
public bool Death = false;
public bool Alive = false;
public bool Muerto;
public GameObject Generador;
public GameObject StartButton;
public CharacterMotor Motor;
public static PlayerManager Instanse;
// Use this for initialization
void Start()
{
Instanse = this;
}
// Update is called once per frame
void Update()
{
if (gameObject.transform.position.y <= -3.5f)
Death = true;
if (!Alive)
Generador.transform.position = new Vector3(0, -0.57f, -4.98f);
if (Death)
{
Generador.transform.position = new Vector3(0, -0.57f, -4.12f);
GenerateManager.Instante.BeforeObject = GenerateManager.Instante.Spawn;
Motor.canControl = false;
StartButton.SetActive(true);
CameraMovement.Instanse.CanMoveCamera = false;
gameObject.transform.position = new Vector3(0.46f, 1.102971f, -6);
Camera.main.transform.position = new Vector3(-0.07402526f, 12.0031f, -1.937099f);
foreach (GameObject gm in GenerateManager.Instante.BloquesGenerados)
{
Destroy(gm);
}
GenerateManager.Instante.BloquesGenerados.Clear();
Death = false;
}
}
void OnTriggerStay(Collider other)
{
Debug.Log(other.tag);
if (other.gameObject.tag == "Generador")
GenerateManager.Instante.DoGenerate = true;
if (other.gameObject.tag == "Muerte")
{
Alive = false;
Death = true;
}
}
}
Add rigidbody component to gameobject,set rigidbody component attribute kinematic=false.

Trouble reveling objects using layer based colliderspheres C# Unity

I'm having some trouble getting a mechanic to function correctly in my game. Basically I have two zones: Collidersight and Colliderfatal, defined by collider spheres that are attached to a artillery shell that is fired by a cannon. Essentially, I want any objects that are within the Collidersight zone to be revealed as long as they are within that particular zone, if they are outside that zone they should return to being invisible. If an object collides with Colliderfatal, then that object should be revealed perminantly, even after the shell has been destroyed. I have tried to initialize the gameObjects individually but this appears to be extremely confusing and not applicable to the situation. The gameobjects already exist within the scene and I am not instantiating them in. I have been told, that I may need to create a list of the gameobjects to loop inside the collidersphere as a potentional solution for this problem but I am totally lost on how this might be achieved.
here is the code.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class zone : MonoBehaviour {
public LayerMask m_SightLayers;
public LayerMask s_FatalityLayers;
public Vector3 m_Position;
public float m_Radius;
public float m_Force;
public float s_Radius;
public Vector3 s_Position;
public Invisible1 revealenemy1;
public Invisible1 enemykill1;
public float s_Force;
public InvisibleKill makeDead;
public GameObject EnemyCube1;
//public GameObject enemydead;
bool hasExploded;
public bool inZone;
public bool inKillzone;
//public float removeTime = 5.0f;
bool hasBeenhit;
void Awake(){
GameObject[] objects = GameObject.FindGameObjectsWithTag("Enemy");
}
void start (){
makeDead = (InvisibleKill) EnemyCube1.GetComponent (typeof(InvisibleKill));
revealenemy1 = (Invisible1) EnemyCube1.GetComponent(typeof(Invisible1));
}
void OnCollisionEnter(Collision explode){
if(explode.gameObject.name == "Terrain" || explode.gameObject.name == "EnemyCube" || explode.gameObject.name == "EnemyCube1" ){
hasExploded = true;
}
}
void FixedUpdate ()
{
if (hasExploded == true){
Collider[] collidersight;
Collider[] colliderfatal;
Rigidbody rigidbody;
collidersight = Physics.OverlapSphere (transform.position + m_Position, m_Radius, m_SightLayers);
foreach (Collider collider in collidersight)
{
if(collider.tag == "Enemy"){
Debug.Log("stuff");
}
rigidbody = (Rigidbody) collider.gameObject.GetComponent (typeof (Rigidbody));
if (rigidbody == null)
{
continue;
}
if(rigidbody.gameObject.tag == "Enemy"){
inZone = true;
if(inZone == true){
revealenemy1.Reveal1();
// revealenemy2.Reveal2();
//revealenemy3.Reveal3();
Debug.Log ("hit");
hasBeenhit = true;
if(hasBeenhit == false){
hasBeenhit = false;
// revealenemy1.Hidden();
//// revealenemy2.Hidden2();
// revealenemy3.Hidden3();
}
}else{
}
}
}
//Debug.Log (hasExploded);
colliderfatal = Physics.OverlapSphere (transform.position + s_Position,s_Radius,s_FatalityLayers);
foreach (Collider collider in colliderfatal)
{
inKillzone = true;
rigidbody = (Rigidbody) collider.gameObject.GetComponent (typeof (Rigidbody));
if (rigidbody ==null)
{
continue;
}
rigidbody.AddExplosionForce (s_Force * -1, transform.position + s_Position,s_Radius);
Debug.Log("hasbeenkilled");
}
}
if(hasBeenhit == false){
revealenemy1.Hidden();
//revealenemy2.Hidden2();
//revealenemy3.Hidden3 ();
hasBeenhit = false;
}
if(inKillzone == true){
//EnemyCube1.GetComponentInChildren (typeof(Invisible1));
hasBeenhit = true;
//revealenemy.renderer.enabled = true;
// makeDead.isdead = true;
//(typeof(Invisible1));
}
if(makeDead.isdead == true){
revealenemy1.Reveal1();
}
}
void OnDrawGizmosSelected () {
Gizmos.color = Color.red;
Gizmos.DrawWireSphere (transform.position + m_Position, m_Radius);
//Gizmos.DrawWireSphere (transform.position + s_Position, s_Radius);
}
void OnDrawGizmos()
{
Gizmos.color = Color.blue;
Gizmos.DrawWireSphere (transform.position + s_Position, s_Radius);
}
}
Why not simply activate/deactivate the object renderers when they enter the zones? You stipulate that objects that have entered the 'Fatal' zone are permanently visible, I took this to mean they are visible even if they leave that zone.
Visibility class to be placed on any object whose visibility you want to change:
public class Visibility : MonoBehaviour {
public bool LockVisibility = false;
public void SetVisible(bool state){
if(LockVisibility)return;
renderer.enabled = state;
}
}
And the collision detection class.
public class CollisionRender : MonoBehaviour {
//example collision types
public enum CollisionTypes { Fatal,InSight };
public CollisionTypes CollisionType = CollisionTypes.InSight;
//turn renderer on.
void OnTriggerEnter(Collider other) {
Visibility vis = other.gameObject.GetComponent<Visibility>();
if(CollisionType == CollisionTypes.InSight){
vis.SetVisible(true);
}else if(CollisionType == CollisionTypes.Fatal){
//if in 'fatal' zone, make visible and lock visibility.
vis.SetVisible(true);
vis.LockVisibility = true;
}
}
void OnTriggerExit(Collider other) {
Visibility vis = other.gameObject.GetComponent<Visibility>();
vis.SetVisible(false);
}
}
I'm using triggers so your collider will need to have 'IsTrigger' checked to work.

Categories