unity multiplayer control not working - c#

Hi I am using uNet Unity Multiplayer and my player controls dose not work properly. i connect 2 devices on 1 device it work good but on other device it does not move left or right nor jump. only local player can move local character
Here is the Code
using UnityEngine;
using System.Collections;
using UnityEngine.Networking;
public class Player1 : NetworkBehaviour
{
private static Player1 playerInstance;
public static Player1 PlayerInstance {
get {
return playerInstance;
}
}
void Awake ()
{
playerInstance = this;
}
public GameObject horseRun;
public GameObject horsesaddleregdoll;
public GameObject pauseCamera;
CharacterController controller;
public Animator anim;
public int horseNum;
public GameObject cam;
void Start ()
{
if (isLocalPlayer) {
controller = GetComponent<CharacterController> ();
transform.position = position2.position;
currentPos = 2;
anim.SetInteger ("horse", 0);
AudioManagerScript.AudioInstence.horseWhinny (horseNum);
} else {
Camera cam = GetComponentInChildren <Camera> ();
cam.enabled = false;
// cam.gameObject.SetActive (false);
// this.enabled = false;
}
Time.timeScale = 0;
position1 = GameObject.Find ("Position1").transform;
position2 = GameObject.Find ("Position2").transform;
position3 = GameObject.Find ("Position3").transform;
position4 = GameObject.Find ("Position4").transform;
}
public float speed = 10.0f;
public Transform position1;
public Transform position2;
public Transform position3;
public Transform position4;
int currentPos = 1;
bool moveFromPos1ToPos2;
bool moveFromPos2ToPos1;
bool moveFromPos2ToPos3;
bool moveFromPos3ToPos2;
bool moveFromPos3ToPos4;
bool moveFromPos4ToPos3;
float timeMove = 0;
public float jumpspeed = 10.0f;
public float gravity = 20.0f;
private Vector3 moveDirection = Vector3.zero;
public Vector2 findDirection;
public Vector2 startPoint;
public Vector2 endPoint;
// Update is called once per frame
void Update ()
{
if (isLocalPlayer) {
timerStep -= Time.deltaTime;
gameObject.transform.position += new Vector3 (0, 0, Time.deltaTime * 80.0f);
if (moveFromPos1ToPos2) {
if (timeMove >= .5f) {
transform.position = new Vector3 (position1.position.x, transform.position.y, transform.position.z);
transform.localEulerAngles = new Vector3 (0, 0, 0);
moveFromPos1ToPos2 = false;
currentPos = 2;
Debug.Log ("Current Pos" + currentPos);
}
timeMove += Time.deltaTime;
transform.position = Vector3.Lerp (new Vector3 (position1.position.x, transform.position.y, transform.position.z), new Vector3 (position2.position.x, transform.position.y, transform.position.z), timeMove * 2);
}
if (moveFromPos2ToPos1) {
if (timeMove >= .5f) {
transform.position = new Vector3 (position2.position.x, transform.position.y, transform.position.z);
transform.localEulerAngles = new Vector3 (0, 0, 0);
moveFromPos2ToPos1 = false;
currentPos = 1;
Debug.Log ("Current Pos" + currentPos);
}
timeMove += Time.deltaTime;
transform.position = Vector3.Lerp (new Vector3 (position2.position.x, transform.position.y, transform.position.z), new Vector3 (position1.position.x, transform.position.y, transform.position.z), timeMove * 2);
}
if (moveFromPos2ToPos3) {
if (timeMove >= .5f) {
transform.position = new Vector3 (position2.position.x, transform.position.y, transform.position.z);
transform.localEulerAngles = new Vector3 (0, 0, 0);
moveFromPos2ToPos3 = false;
currentPos = 3;
Debug.Log ("Current Pos" + currentPos);
}
timeMove += Time.deltaTime;
transform.position = Vector3.Lerp (new Vector3 (position2.position.x, transform.position.y, transform.position.z), new Vector3 (position3.position.x, transform.position.y, transform.position.z), timeMove * 2);
}
if (moveFromPos3ToPos2) {
if (timeMove >= .5f) {
transform.position = new Vector3 (position3.position.x, transform.position.y, transform.position.z);
transform.localEulerAngles = new Vector3 (0, 0, 0);
moveFromPos3ToPos2 = false;
currentPos = 2;
Debug.Log ("Current Pos" + currentPos);
}
timeMove += Time.deltaTime;
transform.position = Vector3.Lerp (new Vector3 (position3.position.x, transform.position.y, transform.position.z), new Vector3 (position2.position.x, transform.position.y, transform.position.z), timeMove * 2);
}
if (moveFromPos3ToPos4) {
if (timeMove >= .5f) {
transform.position = new Vector3 (position3.position.x, transform.position.y, transform.position.z);
transform.localEulerAngles = new Vector3 (0, 0, 0);
moveFromPos3ToPos4 = false;
currentPos = 4;
Debug.Log ("Current Pos" + currentPos);
}
timeMove += Time.deltaTime;
transform.position = Vector3.Lerp (new Vector3 (position3.position.x, transform.position.y, transform.position.z), new Vector3 (position4.position.x, transform.position.y, transform.position.z), timeMove * 2);
}
if (moveFromPos4ToPos3) {
if (timeMove >= .5f) {
transform.position = new Vector3 (position4.position.x, transform.position.y, transform.position.z);
transform.localEulerAngles = new Vector3 (0, 0, 0);
moveFromPos4ToPos3 = false;
currentPos = 3;
Debug.Log ("Current Pos" + currentPos);
}
timeMove += Time.deltaTime;
transform.position = Vector3.Lerp (new Vector3 (position4.position.x, transform.position.y, transform.position.z), new Vector3 (position3.position.x, transform.position.y, transform.position.z), timeMove * 2);
}
moveDirection.y -= gravity * Time.deltaTime;
controller.Move (moveDirection * Time.deltaTime);
}
}
//.................................. Horse Run to Jump & Jump to Run Animation States ......................
public void HorseJumpState ()
{
Debug.Log ("JUMP HORSE" + gameObject.name);
moveDirection.y = jumpspeed;
controller.radius *= 0.5f;
Invoke ("JumpTime", .8f);
Invoke ("HorseRunState", 0.75f);
}
public void HorseRunState ()
{
anim.SetInteger ("horse", 0);
}
public void HorseIdleState ()
{
anim.SetInteger ("horse", 5);
}
float timerStep = 1.25f;
void JumpTime ()
{
controller.radius *= 2;
}
public void JumpButton ()
{
if (isLocalPlayer) {
Time.timeScale = 1;
Debug.Log ("timer" + timerStep);
if (timerStep <= 0 && controller.isGrounded) {
timerStep = 1.25f;
{
anim.SetInteger ("horse", 1);
Invoke ("HorseJumpState", .00001f);
AudioManagerScript.AudioInstence.jumpSound (horseNum);
}
}
}
}
public void SwipeLeft ()
{
if (position1 == null || position2 == null || position3 == null || position4 == null) {
position1 = GameObject.Find ("Position1").transform;
position2 = GameObject.Find ("Position2").transform;
position3 = GameObject.Find ("Position3").transform;
position4 = GameObject.Find ("Position4").transform;
}
Time.timeScale = 1;
if (isLocalPlayer) {
if (currentPos == 2 && controller.isGrounded && !moveFromPos1ToPos2 && !moveFromPos2ToPos1 && !moveFromPos2ToPos3 && !moveFromPos3ToPos2 && !moveFromPos3ToPos4 && !moveFromPos4ToPos3) {
moveFromPos2ToPos1 = true;
transform.localEulerAngles = new Vector3 (0, -15, 0);
timeMove = 0;
} else if (currentPos == 3 && controller.isGrounded && !moveFromPos1ToPos2 && !moveFromPos2ToPos1 && !moveFromPos2ToPos3 && !moveFromPos3ToPos2 && !moveFromPos3ToPos4 && !moveFromPos4ToPos3) {
moveFromPos3ToPos2 = true;
transform.localEulerAngles = new Vector3 (0, -15, 0);
timeMove = 0;
} else if (currentPos == 4 && controller.isGrounded && !moveFromPos1ToPos2 && !moveFromPos2ToPos1 && !moveFromPos2ToPos3 && !moveFromPos3ToPos2 && !moveFromPos3ToPos4 && !moveFromPos4ToPos3) {
moveFromPos4ToPos3 = true;
transform.localEulerAngles = new Vector3 (0, -15, 0);
timeMove = 0;
}
}
}
public void SwipeRight ()
{
if (position1 == null || position2 == null || position3 == null || position4 == null) {
position1 = GameObject.Find ("Position1").transform;
position2 = GameObject.Find ("Position2").transform;
position3 = GameObject.Find ("Position3").transform;
position4 = GameObject.Find ("Position4").transform;
}
Time.timeScale = 1;
if (isLocalPlayer) {
if (currentPos == 1 && controller.isGrounded && !moveFromPos1ToPos2 && !moveFromPos2ToPos1 && !moveFromPos2ToPos3 && !moveFromPos3ToPos2 && !moveFromPos3ToPos4 && !moveFromPos4ToPos3) {
moveFromPos1ToPos2 = true;
transform.localEulerAngles = new Vector3 (0, 15, 0);
timeMove = 0;
} else if (currentPos == 2 && controller.isGrounded && !moveFromPos1ToPos2 && !moveFromPos2ToPos1 && !moveFromPos2ToPos3 && !moveFromPos3ToPos2 && !moveFromPos3ToPos4 && !moveFromPos4ToPos3) {
moveFromPos2ToPos3 = true;
transform.localEulerAngles = new Vector3 (0, 15, 0);
timeMove = 0;
} else if (currentPos == 3 && controller.isGrounded && !moveFromPos1ToPos2 && !moveFromPos2ToPos1 && !moveFromPos2ToPos3 && !moveFromPos3ToPos2 && !moveFromPos3ToPos4 && !moveFromPos4ToPos3) {
moveFromPos3ToPos4 = true;
transform.localEulerAngles = new Vector3 (0, 15, 0);
timeMove = 0;
}
}
}
bool gameOver = false;
void GameOveronTriggerEnter ()
{
if (!gameOver) {
gameOver = true;
GUIManager.GuiInstance.gameOver.SetActive (true);
GUIManager.GuiInstance.GrassObstaclesDestroy ();
GUIManager.GuiInstance.Invoke ("AdsCall", .7f);
AudioManagerScript.AudioInstence.pauseSound ();
GUIManager.GuiInstance.scorecheck ();
}
}
void DisableScript ()
{
GameObject player = GameObject.FindGameObjectWithTag ("Player");
player.GetComponent<Player1> ().enabled = false;
GameObject[] anims = GameObject.FindGameObjectsWithTag ("animator");
for (int i = 0; i < anims.Length; i++)
anims [i].GetComponent<Animator> ().enabled = false;
}
bool gameOverfalse = false;
//.................... Obstacles Triggers .................
void OnTriggerEnter (Collider coll)
{
int grass = GUIManager.GuiInstance.grass;
if (coll.gameObject.tag == "hurdle" || coll.gameObject.tag == "bridgehurdles" && gameOverfalse == false) {
gameOverfalse = true;
horseRun.SetActive (false);
horsesaddleregdoll.SetActive (true);
AudioManagerScript.AudioInstence.horseDie (horseNum);
gameObject.GetComponent<Player1> ().enabled = false;
pauseCamera.SetActive (false);
Invoke ("GameOveronTriggerEnter", 2.0f);
Invoke ("DisableScript", 1.5f);
GUIManager.GuiInstance.gamePanelSingle.SetActive (false);
GUIManager.GuiInstance.singleWater = false;
} else if (coll.gameObject.tag == "Single") {
GUIManager.GuiInstance.score += 10 * grass;
} else if (coll.gameObject.tag == "Double") {
GUIManager.GuiInstance.score += 25 * grass;
} else if (coll.gameObject.tag == "Tripple") {
GUIManager.GuiInstance.score += 50 * grass;
} else if (coll.gameObject.tag == "Forth") {
GUIManager.GuiInstance.score += 100 * grass;
} else if (coll.gameObject.tag == "Grass") {
Debug.Log ("Grass", coll.gameObject);
GUIManager.GuiInstance.grass++;
AudioManagerScript.AudioInstence.Collectable (horseNum);
//GUIManager.GuiInstance.score+= 250*2;
Destroy (coll.gameObject);
} else if (coll.gameObject.tag == "grassreset") {
Debug.Log ("Grass", coll.gameObject);
GUIManager.GuiInstance.grass = 1;
//GUIManager.GuiInstance.score+= 250*2;
Destroy (coll.gameObject);
}
if (coll.gameObject.tag == "snow") {
Debug.Log ("Trigger Enter");
GUIManager.GuiInstance.snow.SetActive (true);
}
}
bool dontMove = false;
//..................While Horse on Bridge ......................
void OnTriggerStay (Collider colstay)
{
if (colstay.gameObject.tag == "Bridge") {
dontMove = true;
Debug.Log ("Trigger Stay");
moveFromPos1ToPos2 = false;
moveFromPos2ToPos1 = false;
transform.localEulerAngles = new Vector3 (0, 0, 0);
// cam.GetComponent<SmoothFollow> ().height = 50;
}
}
void OnTriggerExit (Collider colexit)
{
if (colexit.gameObject.tag == "Bridge") {
dontMove = false;
// cam.GetComponent<SmoothFollow> ().height = 35;
}
if (colexit.gameObject.tag == "snow") {
Debug.Log ("Trigger Exit");
GUIManager.GuiInstance.snow.SetActive (false);
}
}
}

In UNET, Before performing any operation into non-player object you have to first acquire its authority. After getting the authority, you will become able to perform an action that will sync across network.
For details You can check my this answer.

Related

How can i stop the coroutine immediately in the middle once the player is not looking at any target anymore?

When the player is looking at a target the ui text is enabled true and it's showing some text.
void OnAnimatorIK()
{
if (lookObjs != null)
{
lookObjs.RemoveAll(x => x == null);
InteractableItem primaryTarget = null;
float closestLookWeight = 0;
// Here we find the target which is closest (by angle) to the players view line
allDetectedItems.Clear();
foreach (InteractableItem target in lookObjs)
{
if (target.enabledInteraction == false)
{
continue;
}
Vector3 lookAt = target.transform.position - transform.position;
lookAt.y = 0f;
// Filter out all objects that are too far away
if (lookAt.magnitude > target.distance) continue;
RaycastHit hit;
if (Physics.Raycast(playerEyes.transform.position, target.transform.position - playerEyes.transform.position, out hit, target.distance, ~LayerMask.GetMask("kid_from_space")))
{
if (hit.collider.gameObject == target.gameObject)
{
float dotProduct = Vector3.Dot(new Vector3(transform.forward.x, 0f, transform.forward.z).normalized, lookAt.normalized);
float lookWeight = Mathf.Clamp(dotProduct, 0f, 1f);
if (lookWeight > 0.1f && lookWeight > closestLookWeight)
{
closestLookWeight = lookWeight;
primaryTarget = target;
if (showText && primaryTarget.description != "")
{
StartCoroutine(WaitBeforeShowingText(primaryTarget));
showText = false;
}
}
allDetectedItems.Add(target);
}
else
{
showText = true;
text.text = "";
descriptionTextImage.SetActive(false);
}
}
}
InteractWithTarget(primaryTarget, closestLookWeight);
}
}
This line start the coroutine that showing the text :
StartCoroutine(WaitBeforeShowingText(primaryTarget));
and inside the coroutine
IEnumerator WaitBeforeShowingText(InteractableItem primaryTarget)
{
yield return new WaitForSeconds(1f);
descriptionTextImage.SetActive(true);
text.text = primaryTarget.description;
}
i did it because i wanted to give some delay before showing the text when the player is looking at a target.
the problem is if the coroutine started but before even showing the text i'm rotating the player to NOT looking at any target but because the coroutine started already it will show the text even if the player is not looking anymore at any target.
so the coroutine must be stopped somehow in the middle and show no text.
another possible problem is what if there are two close targets and i move/rotate the player so the target he is looking at will change too fast for the coroutine ?
This is the full code :
using UnityEngine;
using System;
using System.Collections;
using UnityEngine.UI;
using System.Collections.Generic;
using System.Linq;
using TMPro;
[RequireComponent(typeof(Animator))]
public class IKControl : MonoBehaviour
{
public List<InteractableItem> lookObjs = new List<InteractableItem>();
public TextMeshProUGUI text;
public float weightDamping = 1.5f;
public bool RightHandToTarget = false;
public GameObject descriptionTextImage;
public float duration;
private List<InteractableItem> allDetectedItems;
private Animator animator;
private InteractableItem lastPrimaryTarget;
private float lerpEndDistance = 0.1f;
private float finalLookWeight = 0;
private bool transitionToNextTarget = false;
private float t;
private bool showText = true;
private GameObject playerEyes;
void Start()
{
playerEyes = GameObject.Find("rig_head");//"rig_eye.L");
animator = GetComponent<Animator>();
allDetectedItems = new List<InteractableItem>();
t = 0;
}
// Callback for calculating IK
void OnAnimatorIK()
{
if (lookObjs != null)
{
lookObjs.RemoveAll(x => x == null);
InteractableItem primaryTarget = null;
float closestLookWeight = 0;
// Here we find the target which is closest (by angle) to the players view line
allDetectedItems.Clear();
foreach (InteractableItem target in lookObjs)
{
if (target.enabledInteraction == false)
{
continue;
}
Vector3 lookAt = target.transform.position - transform.position;
lookAt.y = 0f;
// Filter out all objects that are too far away
if (lookAt.magnitude > target.distance) continue;
RaycastHit hit;
if (Physics.Raycast(playerEyes.transform.position, target.transform.position - playerEyes.transform.position, out hit, target.distance, ~LayerMask.GetMask("kid_from_space")))
{
if (hit.collider.gameObject == target.gameObject)
{
// First object hit was the target so there is a clear line of sight
//Debug.DrawRay(playerEyes.transform.position, Vector3.forward, Color.red);
float dotProduct = Vector3.Dot(new Vector3(transform.forward.x, 0f, transform.forward.z).normalized, lookAt.normalized);
float lookWeight = Mathf.Clamp(dotProduct, 0f, 1f);
if (lookWeight > 0.1f && lookWeight > closestLookWeight)
{
closestLookWeight = lookWeight;
primaryTarget = target;
if (showText && primaryTarget.description != "")
{
StartCoroutine(WaitBeforeShowingText(primaryTarget));
showText = false;
}
}
allDetectedItems.Add(target);
}
else
{
showText = true;
text.text = "";
descriptionTextImage.SetActive(false);
}
}
}
InteractWithTarget(primaryTarget, closestLookWeight);
}
}
private void InteractWithTarget(InteractableItem primaryTarget, float closestLookWeight)
{
if (primaryTarget != null)
{
if ((lastPrimaryTarget != null) && (lastPrimaryTarget != primaryTarget) && (finalLookWeight > 0f))
{
// Here we start a new transition because the player looks already to a target but
// we have found another target the player should look at
transitionToNextTarget = true;
}
}
// The player is in a neutral look position but has found a new target
if ((primaryTarget != null) && !transitionToNextTarget)
{
if (primaryTarget.IsAnyAction())
{
RightHandToTarget = true;
}
lastPrimaryTarget = primaryTarget;
finalLookWeight = Mathf.Lerp(finalLookWeight, 1f, Time.deltaTime * weightDamping);
float bodyWeight = finalLookWeight * .1f;
animator.SetLookAtWeight(finalLookWeight, bodyWeight, 1f);
animator.SetLookAtPosition(primaryTarget.transform.position);
if (RightHandToTarget && primaryTarget.IsAnyAction())
{
Vector3 relativePos = primaryTarget.transform.position - transform.position;
Quaternion rotationtoTarget = Quaternion.LookRotation(relativePos, Vector3.up);
if (primaryTarget.interactableMode == InteractableItem.InteractableMode.ActionWithoutThrow)
{
animator.SetIKRotationWeight(AvatarIKGoal.RightHand, finalLookWeight);
animator.SetIKRotation(AvatarIKGoal.RightHand, rotationtoTarget);
animator.SetIKPositionWeight(AvatarIKGoal.RightHand, finalLookWeight * 1f * closestLookWeight);
animator.SetIKPosition(AvatarIKGoal.RightHand, primaryTarget.transform.position);
}
if (primaryTarget.interactableMode == InteractableItem.InteractableMode.Action)
{
animator.SetIKRotationWeight(AvatarIKGoal.RightHand, finalLookWeight);
animator.SetIKRotation(AvatarIKGoal.RightHand, rotationtoTarget);
animator.SetIKPositionWeight(AvatarIKGoal.RightHand, finalLookWeight * 0.1f * closestLookWeight);
animator.SetIKPosition(AvatarIKGoal.RightHand, primaryTarget.transform.position);
}
}
}
// Let the player smoothly look away from the last target to the neutral look position
if ((primaryTarget == null && lastPrimaryTarget != null) || transitionToNextTarget)
{
finalLookWeight = Mathf.Lerp(finalLookWeight, 0f, t / duration);//Time.deltaTime * weightDamping);
t += Time.deltaTime;
float bodyWeight = finalLookWeight * .1f;
animator.SetLookAtWeight(finalLookWeight, bodyWeight, 1f);
animator.SetLookAtPosition(lastPrimaryTarget.transform.position);
if (RightHandToTarget)
{
Vector3 relativePos = lastPrimaryTarget.transform.position - transform.position;
Quaternion rotationtoTarget = Quaternion.LookRotation(relativePos, Vector3.up);
animator.SetIKRotationWeight(AvatarIKGoal.RightHand, finalLookWeight);
animator.SetIKRotation(AvatarIKGoal.RightHand, rotationtoTarget);
animator.SetIKPositionWeight(AvatarIKGoal.RightHand, finalLookWeight * 0.5f * closestLookWeight);
animator.SetIKPosition(AvatarIKGoal.RightHand, lastPrimaryTarget.transform.position);
}
if (finalLookWeight < lerpEndDistance)
{
showText = true;
text.text = "";
descriptionTextImage.SetActive(false);
transitionToNextTarget = false;
finalLookWeight = 0f;
lastPrimaryTarget = null;
transform.rotation = Quaternion.Euler(0, transform.eulerAngles.y, 0);
}
}
}
IEnumerator WaitBeforeShowingText(InteractableItem primaryTarget)
{
yield return new WaitForSeconds(1f);
descriptionTextImage.SetActive(true);
text.text = primaryTarget.description;
}
}
To stop a Coroutine, call StopCoroutine(WaitBeforeShowingText);
Here is the doc :
https://docs.unity3d.com/ScriptReference/MonoBehaviour.StopCoroutine.html

Rotate objects with touch in unity

I want to rotate an object with touch in unity. I touch is moved left object should rotate leftward as long as user holds the touch and vice versa.
My code rotates the object correctly as long as touch is moved leftward or rightward. Later if touch movement is stopped and hold, object starts rotating rightward. Here is what i have tried.
{
if (Input.touchCount > 0)
{
touch = Input.GetTouch(0);
if (touch.phase == TouchPhase.Began)
{
oldTouchPosition = touch.position;
}
else if (touch.phase == TouchPhase.Moved)
{
if (touch.deltaPosition.x > 10f)
{
rotateLeftward = false;
rotateRightward = true;
}
else if (touch.deltaPosition.x < 10f)
{
rotateRightward = false;
rotateLeftward = true;
}
}
if(rotateLeftward == true )
{
RotateLeftWard();
}
else if (rotateRightward == true)
{
RotateRightWard();
}
}
}
void RotateLeftWard()
{
transform.rotation = Quaternion.Euler(0f, 1 * keepRotateSpeed, 0f) * transform.rotation;
}
void RotateRightWard()
{
transform.rotation = Quaternion.Euler(0f, -1 * keepRotateSpeed, 0f) * transform.rotation;
}
I think there is no code that sets the both rotations to false..
I was able to code a perfect solution for all this using the code below
I hope it will be useful
private Touch touch;
private Vector2 oldTouchPosition;
private Vector2 NewTouchPosition;
[SerializeField]
private float keepRotateSpeed = 10f;
private void Update()
{
RotateThings();
}
private void RotateThings()
{
if (Input.touchCount > 0)
{
touch = Input.GetTouch(0);
if (touch.phase == TouchPhase.Began)
{
oldTouchPosition = touch.position;
}
else if (touch.phase == TouchPhase.Moved)
{
NewTouchPosition = touch.position;
}
Vector2 rotDirection = oldTouchPosition - NewTouchPosition;
Debug.Log(rotDirection);
if (rotDirection.x < 0 )
{
RotateRight();
}
else if (rotDirection.x > 0 )
{
RotateLeft();
}
}
}
void RotateLeft()
{
transform.rotation = Quaternion.Euler(0f, 1.5f * keepRotateSpeed, 0f) * transform.rotation;
}
void RotateRight()
{
transform.rotation = Quaternion.Euler(0f, -1.5f * keepRotateSpeed, 0f) * transform.rotation;
}
Same as Gurbrinder Singh posted, but a bit advanced with a deltaThreshold
private Touch touch;
private Vector2 oldTouchPosition;
private Vector2 NewTouchPosition;
[SerializeField]
private float keepRotateSpeed = 10f;
[SerializeField]
private float deltaThreshold = 5f;
private void Update()
{
RotateThings();
}
private void RotateThings()
{
if (Input.touchCount > 0)
{
touch = Input.GetTouch(0);
if (touch.phase == TouchPhase.Began)
{
oldTouchPosition = touch.position;
NewTouchPosition = touch.position;
}
else if (touch.phase == TouchPhase.Moved)
{
oldTouchPosition = NewTouchPosition;
NewTouchPosition = touch.position;
}
float delta = Mathf.Abs(oldTouchPosition.x - NewTouchPosition.x);
if (/*touch.phase != TouchPhase.Stationary &&*/ delta >= deltaThreshold)
{
Vector2 rotDirection = oldTouchPosition - NewTouchPosition;
Debug.Log(delta);
if (rotDirection.x < 0)
{
RotateRight();
}
else if (rotDirection.x > 0)
{
RotateLeft();
}
}
}
}
void RotateLeft()
{
transform.rotation = Quaternion.Euler(0f, 1.5f * keepRotateSpeed, 0f) * transform.rotation;
}
void RotateRight()
{
transform.rotation = Quaternion.Euler(0f, -1.5f * keepRotateSpeed, 0f) * transform.rotation;
}
Something like this will work if you want a little more control
private float _lastTouchRot = float.NegativeInfinity;
...
private void UpdateMobile()
{
if (UnityEngine.Input.touchCount == 2)
{
var touch0 = Input.GetTouch(0);
var touch1 = Input.GetTouch(1);
var touchRot = Vector2.SignedAngle(touch0.position - touch1.position, Vector2.right);
if(this._lastTouchRot == float.NegativeInfinity) this._lastTouchRot = touchRot;
var delta = this._lastTouchRot - touchRot;
this._angle += delta;
this._lastTouchRot = touchRot;
if(touch0.phase == TouchPhase.Ended || touch1.phase == TouchPhase.Ended)
this._lastTouchRot = float.NegativeInfinity;
}
}

How to fix 2D animation while player walks?

I'm trying to make my character idle, run, jump and fall. I did it, but i have bug with runing animation. While he goes left or right, he doesn't play animation "run", which called by integer "noob" with parameter "2",he plays animation "fall", which "noob" is parameter "4"
I'm using Unity 4.5.x and C# code
using UnityEngine;
using System.Collections;
public class movement : MonoBehaviour {
Rigidbody2D rb;
Animator anim;
public int jumpCount = 0;
public Camera main;
float jumpTimer = 0;
void Start () {
rb = GetComponent<Rigidbody2D> ();
anim = GetComponent<Animator>();
}
void Update () {
if (Input.GetKeyDown (KeyCode.X) && jumpCount < 2 && jumpTimer == 0) {
jump ();
jumpCount += 1;
jumpTimer = 1;
StartCoroutine("jumpTime");
}
if (rb.velocity.y > 0) {
Flip();
anim.SetInteger ("noob", 3);
}
if (rb.velocity.y < 0) {
Flip();
anim.SetInteger ("noob", 4);
}
if (Input.GetAxis ("Horizontal") == 0 && rb.velocity.y == 0) {
anim.SetInteger ("noob", 1);
}
if (rb.velocity.y == 0 && Input.GetAxis ("Horizontal") != 0) {
Flip();
anim.SetInteger("noob", 2);
}
if (rb.velocity.y == 0) {
jumpCount = 0;
}
}
void FixedUpdate(){
rb.velocity = new Vector2 (Input.GetAxis ("Horizontal") * 12f, rb.velocity.y);
}
void jump(){
rb.AddForce (transform.up * 14F, ForceMode2D.Impulse);
}
void Flip() {
if (Input.GetAxis ("Horizontal") > 0) {
transform.localRotation = Quaternion.Euler (0, 0, 0);
}
if (Input.GetAxis ("Horizontal") < 0) {
transform.localRotation = Quaternion.Euler (0, 180, 0);
}
}
IEnumerator jumpTime() {
yield return new WaitForSeconds (0.4f);
jumpTimer = 0;
}
}
I tried to do something with jumCount, jumpTimer and velocity.y, but nothing helped
I would suggested making a grounded and jumping bool, you can use this bool to determine whether your character is airbourne. Also using else if conditional statements may help here to avoid setting your value more than once. Then you can do something like this:
if (grounded && jumping) {
Flip();
anim.SetInteger ("noob", 3);
jumping = false;
}
else if (!grounded) {
Flip();
anim.SetInteger ("noob", 4);
}
else if (Input.GetAxis ("Horizontal") == 0 && grounded) {
anim.SetInteger ("noob", 1);
}
else if (grounded && Input.GetAxis ("Horizontal") != 0) {
Flip();
anim.SetInteger("noob", 2);
}

transform.Rotate(0f, 180f, 0f); rotates the 2D sprite, but not it's children

I'm trying to achieve firing from a 2D Player, attached the "spawn point" and made it a child of the Player, when I try to flip the sprite it works, but it does not flip the "spawn point" so when I turn left, my "spawn point" is still looking right, so when I shoot, the bullets go to the left, not to the right.
Full script:
public class PlayerController : MonoBehaviour
{
void FixedUpdate()
{
RaycastHit2D hit = Physics2D.BoxCast(this.transform.position, new Vector2(0.4f, 0.1f), 0f, Vector2.down, groundCheckRadius, groundMask); //using this for a bigger and more accurate ground check
isTouchingGround = (hit.collider != null) ? true : false;
movementInput = Input.GetAxis("Horizontal");
CheckIfStuck(); //Checks if Mario is trying to walk into the wall and get stuck
if (!isDead)
{
if ((playerRigidbody2D.velocity.x > 0 && !isFacingRight) || (playerRigidbody2D.velocity.x < 0 && isFacingRight))
{
playerAnimator.SetBool("turning", true);
}
else
{
playerAnimator.SetBool("turning", false);
}
float movementForceMultiplier = Mathf.Max(maxHorizontalSpeed - Mathf.Abs(playerRigidbody2D.velocity.x), 1);
playerRigidbody2D.AddForce(new Vector2(movementInput * movementForce * movementForceMultiplier, 0));
playerRigidbody2D.velocity = new Vector2(Mathf.Clamp(playerRigidbody2D.velocity.x, -maxHorizontalSpeed, maxHorizontalSpeed), Mathf.Clamp(playerRigidbody2D.velocity.y, -maxVerticalSpeed, maxVerticalSpeed));
if (Input.GetKeyDown(KeyCode.Space))
{
if (isTouchingGround)
{
//Play Jump sound
if (!poweredUp)
audioSource.PlayOneShot(smallJumpSound);
else
audioSource.PlayOneShot(bigJumpSound);
isJumping = true;
playerRigidbody2D.velocity = new Vector2(playerRigidbody2D.velocity.x, jumpVelocity);
jumpTimeCounter = jumpTime;
}
}
if (jumpTimeCounter > 0 && isJumping)
if (Input.GetKey(KeyCode.Space))
{
jumpTimeCounter -= Time.deltaTime;
{
playerRigidbody2D.velocity = new Vector2(playerRigidbody2D.velocity.x, jumpVelocity);
}
}
if (Input.GetKeyUp(KeyCode.Space))
{
isJumping = false;
jumpTimeCounter = 0;
}
playerAnimator.SetFloat("movementSpeed", Mathf.Abs(playerRigidbody2D.velocity.x));
playerAnimator.SetBool("touchingGround", isTouchingGround);
}
if (movementInput > 0 && !isFacingRight)
{
FlipSprite();
}
else if (movementInput < 0 && isFacingRight)
{
FlipSprite();
}
}
void FlipSprite()
{
isFacingRight = !isFacingRight;
//Vector3 tempScale = transform.localScale;
//tempScale.x *= -1;
//transform.localScale = tempScale;
transform.Rotate(0f, 180f, 0f);
}
}
Flip method:
void FlipSprite()
{
isFacingRight = !isFacingRight;
//Vector3 tempScale = transform.localScale;
//tempScale.x *= -1;
//transform.localScale = tempScale;
transform.Rotate(0f, 180f, 0f);
}

Cannot call or set a variable from another script in C#

EDIT Full Scripts:
SoldierController Script (removed few variables due to character limitaton). I have declared 1 new variable called DontMove and want this to be called from the ElevatorOpen script. Issue I am having is calling this script even though this is set to static and public.
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(Rigidbody))]
[RequireComponent(typeof(CapsuleCollider))]
public class SoldierController : MonoBehaviour
{
#region Variables
public Transform gunPoint;
public GameObject bulletPrefab;
//Components
protected Animator animator;
private GameObject camera;
private Camera cam;
public GameObject splashFX;
public AudioClip gunShotSound;
//action variables
public static bool dontMove = false;
public float walkSpeed = 1.35f;
bool canwalk = true;
float moveSpeed;
public float runSpeed = 1f;
public float rotationSpeed = 20f;
bool isMoving = false;
public bool walking = true;
bool areWalking;
Vector3 newVelocity;
Vector3 inputVec;
//aiming/shooting variables
bool canAim;
bool canFire = true;
public bool aiming = true;
bool isAiming = false;
public bool grenading = true;
bool isGrenading;
bool canGrenade = true;
int weaponType = 0;
//Weapon Prefabs
GameObject pistol;
GameObject rifle;
GameObject launcher;
GameObject heavy;
#endregion
#region Initialization
void Start()
{
canMove = true;
//dontMove = false;
//set the animator component
animator = GetComponentInChildren<Animator>();
//sets the weight on any additional layers to 1
if (animator.layerCount >= 2)
{
animator.SetLayerWeight(1, 1);
}
//Get the camera
camera = GameObject.FindGameObjectWithTag("MainCamera");
cam = camera.GetComponent<Camera>();
//sets the Weapon to 1 in the animator
weaponType = 1;
StartCoroutine(COSwitchWeapon("Weapon", 1));
}
#endregion
#region Update
void Update()
{
x = Input.GetAxisRaw("Horizontal");
//z = Input.GetAxisRaw("Vertical");
inputVec = new Vector3(x, 0, z);
if (animator)
{
CoverUpdate();
JumpingUpdate();
if (!isSwimming) //character can't do any actions while swimming
{
if (Input.GetKeyDown(KeyCode.LeftControl) && canFire && cover != 1 && covering)
{
Fire();
}
if (Input.GetMouseButtonDown(0) && canFire && cover != 1 && covering)
{
Fire();
}
if (Input.GetButton("Fire2") && canAim && aiming)
{
isAiming = true;
}
else
{
isAiming = false;
}
}
}
}
#endregion
#region Fixed/Late Updates
void FixedUpdate()
{
CheckForGrounded();
if (!isSwimming) //character is not swimming
{
//gravity
GetComponent<Rigidbody>().AddForce(0, gravity, 0, ForceMode.Acceleration);
if (aircontrol)
AirControl();
//check if we aren't in cover and can move
if (!covered && canMove)
{
if (canPushPull)
{
if (!isPushPulling)
moveSpeed = UpdateMovement(); //if we are not pushpull use normal movement speed
else
moveSpeed = PushPull(); //we are push pulling, use pushpullspeed
}
else
moveSpeed = UpdateMovement();
}
}
else //character is swimming
{
moveSpeed = Swimming();
}
}
void LateUpdate()
{
//Get local velocity of charcter
float velocityXel = transform.InverseTransformDirection(GetComponent<Rigidbody>().velocity).x;
float velocityZel = transform.InverseTransformDirection(GetComponent<Rigidbody>().velocity).z;
//Update animator with movement values
animator.SetFloat("Velocity X", velocityXel / runSpeed);
animator.SetFloat("Velocity Z", velocityZel / runSpeed);
//if we are moving, set our animator
if (moveSpeed > 0)
{
isMoving = true;
animator.SetBool("Moving", true);
}
else
{
isMoving = false;
animator.SetBool("Moving", false);
}
}
#endregion
void RotateTowardsMovementDir()
{
// Rotation
if (inputVec != Vector3.zero && !isAiming)
{
transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(inputVec), Time.deltaTime * rotationSpeed);
}
}
#region UpdateMovement
float UpdateMovement()
{
Vector3 motion = inputVec;
if (isGrounded)
{
//reduce input for diagonal movement
motion *= (Mathf.Abs(inputVec.x) == 1 && Mathf.Abs(inputVec.z) == 1) ? .7f : 1;
//apply velocity based on platform speed to prevent sliding
float platformVelocity = platformSpeed.magnitude * .4f;
Vector3 platformAdjust = platformSpeed * platformVelocity;
//set speed by walking / running
if (areWalking)
{
canAim = false;
//check if we are on a platform and if its animated, apply the platform's velocity
if (!platformAnimated)
{
newVelocity = motion * walkSpeed + platformAdjust;
}
else
{
newVelocity = motion * walkSpeed + platformAdjust;
}
}
else
{
//check if we are on a platform and if its animated, apply the platform's velocity
if (!platformAnimated)
{
newVelocity = motion * runSpeed + platformAdjust;
}
else
{
newVelocity = motion * runSpeed + platformSpeed;
}
}
}
else
{
//if we are falling use momentum
newVelocity = GetComponent<Rigidbody>().velocity;
}
// limit velocity to x and z, by maintaining current y velocity:
newVelocity.y = GetComponent<Rigidbody>().velocity.y;
GetComponent<Rigidbody>().velocity = newVelocity;
if (!isAiming)
RotateTowardsMovementDir();
//if the right mouse button is held look at the mouse cursor
if (isAiming)
{
//make character point at mouse
Quaternion targetRotation;
float rotationSpeed = 40f;
Vector3 mousePos = Input.mousePosition;
mousePos = cam.ScreenToWorldPoint(new Vector3(mousePos.x, mousePos.y, cam.transform.position.y - transform.position.y));
targetRotation = Quaternion.LookRotation(mousePos - new Vector3(transform.position.x, 0, transform.position.z));
transform.eulerAngles = Vector3.up * Mathf.MoveTowardsAngle(transform.eulerAngles.y, targetRotation.eulerAngles.y, (rotationSpeed * Time.deltaTime) * rotationSpeed);
}
//calculate the rolling time
rollduration -= rolldamp;
if (rollduration > 0)
{
isRolling = true;
}
else
{
isRolling = false;
}
if (isRolling)
{
Vector3 localforward = transform.TransformDirection(0, 0, 1);
GetComponent<Rigidbody>().velocity = localforward * rollSpeed;
}
//return a movement value for the animator
return inputVec.magnitude;
}
#endregion
#region AirControl
void AirControl()
{
float x = Input.GetAxisRaw("Horizontal");
float z = Input.GetAxisRaw("Vertical");
Vector3 inputVec = new Vector3(x, 0, z);
Vector3 motion = inputVec;
motion *= (Mathf.Abs(inputVec.x) == 1 && Mathf.Abs(inputVec.z) == 1) ? .7f : 1;
//allow some control the air
GetComponent<Rigidbody>().AddForce(motion * inAirSpeed, ForceMode.Acceleration);
//limit the amount of velocity we can achieve
float velocityX = 0;
float velocityZ = 0;
if (GetComponent<Rigidbody>().velocity.x > maxVelocity)
{
velocityX = GetComponent<Rigidbody>().velocity.x - maxVelocity;
if (velocityX < 0)
velocityX = 0;
GetComponent<Rigidbody>().AddForce(new Vector3(-velocityX, 0, 0), ForceMode.Acceleration);
}
if (GetComponent<Rigidbody>().velocity.x < minVelocity)
{
velocityX = GetComponent<Rigidbody>().velocity.x - minVelocity;
if (velocityX > 0)
velocityX = 0;
GetComponent<Rigidbody>().AddForce(new Vector3(-velocityX, 0, 0), ForceMode.Acceleration);
}
if (GetComponent<Rigidbody>().velocity.z > maxVelocity)
{
velocityZ = GetComponent<Rigidbody>().velocity.z - maxVelocity;
if (velocityZ < 0)
velocityZ = 0;
GetComponent<Rigidbody>().AddForce(new Vector3(0, 0, -velocityZ), ForceMode.Acceleration);
}
if (GetComponent<Rigidbody>().velocity.z < minVelocity)
{
velocityZ = GetComponent<Rigidbody>().velocity.z - minVelocity;
if (velocityZ > 0)
velocityZ = 0;
GetComponent<Rigidbody>().AddForce(new Vector3(0, 0, -velocityZ), ForceMode.Acceleration);
}
}
#endregion
#region Swimming
float Swimming()
{
Vector3 motion = inputVec;
motion *= (Mathf.Abs(inputVec.x) == 1 && Mathf.Abs(inputVec.z) == 1) ? .7f : 1;
//movement is using swimSpeed
GetComponent<Rigidbody>().AddForce(motion * swimSpeed, ForceMode.Acceleration);
//limit the amount of velocity we can achieve
float velocityX = 0;
float velocityZ = 0;
if (GetComponent<Rigidbody>().velocity.x > maxVelocity)
{
velocityX = GetComponent<Rigidbody>().velocity.x - maxVelocity;
if (velocityX < 0)
velocityX = 0;
GetComponent<Rigidbody>().AddForce(new Vector3(-velocityX, 0, 0), ForceMode.Acceleration);
}
if (GetComponent<Rigidbody>().velocity.x < minVelocity)
{
velocityX = GetComponent<Rigidbody>().velocity.x - minVelocity;
if (velocityX > 0)
velocityX = 0;
GetComponent<Rigidbody>().AddForce(new Vector3(-velocityX, 0, 0), ForceMode.Acceleration);
}
if (GetComponent<Rigidbody>().velocity.z > maxVelocity)
{
velocityZ = GetComponent<Rigidbody>().velocity.z - maxVelocity;
if (velocityZ < 0)
velocityZ = 0;
GetComponent<Rigidbody>().AddForce(new Vector3(0, 0, -velocityZ), ForceMode.Acceleration);
}
if (GetComponent<Rigidbody>().velocity.z < minVelocity)
{
velocityZ = GetComponent<Rigidbody>().velocity.z - minVelocity;
if (velocityZ > 0)
velocityZ = 0;
GetComponent<Rigidbody>().AddForce(new Vector3(0, 0, -velocityZ), ForceMode.Acceleration);
}
RotateTowardsMovementDir();
//return a movement value for the animator
return inputVec.magnitude;
}
#endregion
#region PushPull
float PushPull()
{
//set bools
canAim = false;
canAbility = false;
canCover = false;
canFire = false;
canGrenade = false;
canItem = false;
canJump = false;
canMelee = false;
canReload = false;
canRoll = false;
canSignal = false;
canwalk = false;
isPushPulling = true;
animator.SetBool("PushPull", true);
Vector3 motion = inputVec;
//reduce input for diagonal movement
motion *= (Mathf.Abs(inputVec.x) == 1 && Mathf.Abs(inputVec.z) == 1) ? .7f : 1;
//movement is using pushpull speed
GetComponent<Rigidbody>().velocity = motion * pushPullSpeed;
//return a movement value for the animator
return inputVec.magnitude;
}
#endregion
#region Grounding
void CheckForGrounded()
{
float distanceToGround;
float threshold = .45f;
RaycastHit hit;
Vector3 offset = new Vector3(0, .4f, 0);
if (Physics.Raycast((transform.position + offset), -Vector3.up, out hit, 100f))
{
distanceToGround = hit.distance;
if (distanceToGround < threshold)
{
isGrounded = true;
//moving platforms
if (hit.transform.tag == "Platform")
{
//get platform script from collided platform
Platform platformScript = hit.transform.GetComponent<Platform>();
//check if the platform is moved with physics or if it is animated and get velocity from it
if (platformScript.animated)
{
platformSpeed = platformScript.velocity;
platformAnimated = true;
}
if (!platformScript.animated)
{
platformSpeed = hit.transform.GetComponent<Rigidbody>().velocity;
}
//get the platform rotation to pass into our character when they are on a platform
platformFacing = hit.transform.rotation;
}
else
{
//if we are not on a platform, reset platform variables
platformSpeed = new Vector3(0, 0, 0);
platformFacing.eulerAngles = new Vector3(0, 0, 0);
Platform platformScript = null;
float platformVelocity = 0f;
}
}
else
{
isGrounded = false;
}
}
}
#endregion
#region Cover
void CoverUpdate()
{
/*
if (covering && !isSwimming)
{
//check if we press cover button
if (Input.GetButtonDown("Cover") && canCover && !covered)
{
//set variables
animator.SetBool("Moving", false);
Input.ResetInputAxes();
isMoving = false;
animator.SetBool("Moving", false);
covered = true;
canReload = true;
canCover = false;
canItem = false;
canMelee = false;
canFire = false;
canItem = false;
canGrenade = false;
canJump = false;
cover = 1;
animator.SetInteger("Cover", 1);
GetComponent<Rigidbody>().velocity = new Vector3(0, 0, 0);
}
else
{
//if we are already in cover and press the cover button, get out of cover
if (Input.GetButtonDown("Cover") && covered == true)
{
//set the animation back to idle
animator.SetInteger("Cover", 3);
//set variables
cover = 0;
covered = false;
canCover = true;
canAbility = true;
canAim = true;
canItem = true;
canGrenade = true;
canFire = true;
}
}
}*/
}
#endregion
#region Jumping
void JumpingUpdate()
{
if (!isSwimming) //if character is not swimming
{
//If the character is on the ground
if (isGrounded)
{
//set the animation back to idle
animator.SetInteger("Jumping", 0);
//set variables
jumped = false;
//check if we press jump button
if (canJump && Input.GetButtonDown("Jump") && cover != 1)
{
// Apply the current movement to launch velocity
GetComponent<Rigidbody>().velocity += jumpSpeed * Vector3.up;
//set variables
animator.SetTrigger("Jump");
animator.SetInteger("Jumping", 2);
}
}
else
{
//set bools
canDoubleJump = true;
if (!falling && !jumped)
{
//set the animation back to idle
animator.SetInteger("Jumping", 2);
falling = true;
}
//if double jumping is allowed and jump is pressed, do a double jump
if (canDoubleJump && doublejumping && Input.GetButtonDown("Jump") && doublejumped != true && doublejumping)
{
// Apply the current movement to launch velocity
GetComponent<Rigidbody>().velocity += doublejumpSpeed * Vector3.up;
//set the animation to double jump
animator.SetInteger("Jumping", 3);
//set variables
canJump = false;
doublejumped = true;
isJumping = true;
falling = false;
jumped = false;
}
}
}
else //characer is swimming
{
//check if we press jump button
if (canSwim && Input.GetButtonDown("Jump"))
{
if (x != 0 || z != 0) //if the character movement input is not 0, swim in facing direction
{
// Apply the current movement to launch velocity
GetComponent<Rigidbody>().velocity += swimBurstSpeed * transform.forward;
animator.SetTrigger("SwimBurst");
}
else //we are not trying to move the character, jump up
{
// Apply the current movement to launch velocity
GetComponent<Rigidbody>().velocity = jumpSpeed * Vector3.up;
//set variables
animator.SetTrigger("Jump");
canJump = false;
isJumping = true;
canDoubleJump = true;
jumped = true;
animator.SetInteger("Jumping", 2);
}
}
}
}
#endregion
#region Misc Methods
void Rolling()
{
StartCoroutine(COPlayOneShot("Rolling"));
covered = false;
canCover = false;
cover = 0;
animator.SetInteger("Cover", 0);
isRolling = true;
}
void Fire()
{
StartCoroutine(COPlayOneShot("Fire"));
(Instantiate(bulletPrefab, gunPoint.position, transform.root.rotation) as GameObject).GetComponent<BulletController>().damage = 20;
StartCoroutine(WeaponCooldown());
GetComponent<AudioSource>().PlayOneShot(gunShotSound);
}
IEnumerator WeaponCooldown()
{
canFire = false;
yield return new WaitForSeconds(0.1f);
canFire = true;
}
void Ability()
{
StartCoroutine(COPlayOneShot("Ability"));
}
void Item()
{
StartCoroutine(COPlayOneShot("Item"));
}
void Grenade()
{
StartCoroutine(COGrenade());
isGrenading = true;
}
void Reload()
{
StartCoroutine(COReload(weaponType));
isReloading = true;
}
void Signal()
{
StartCoroutine(COPlayOneShot("Signal"));
}
void Melee()
{
StartCoroutine(COMelee());
isMelee = true;
}
void Pain()
{
StartCoroutine(COPlayOneShot("Pain"));
}
//plays a random death# animation between 1-3
void Death()
{
//stop character movement
animator.SetBool("Moving", true);
Input.ResetInputAxes();
isMoving = false;
int deathnumber = 5;
animator.SetInteger("Death", deathnumber);
}
#endregion
#region CORoutines
//function to play a one shot animation
public IEnumerator COPlayOneShot(string paramName)
{
animator.SetBool(paramName, true);
yield return null;
animator.SetBool(paramName, false);
}
//function to switch weapons
public IEnumerator COSwitchWeapon(string weaponname, int weaponnumber)
{
//sets Weapon to 0 first to reset
animator.SetInteger(weaponname, 0);
yield return null;
yield return null;
animator.SetInteger(weaponname, weaponnumber);
}
//function to reload
public IEnumerator COReload(int weapon)
{
//sets Weapon to 0 first to reset
animator.SetBool("Reload", true);
yield return null;
animator.SetBool("Reload", false);
float wait = 0;
if (weaponType == 1 || weaponType == 2)
{
wait = 1.85f;
}
if (weaponType == 3 || weaponType == 4)
{
wait = 3f;
}
yield return new WaitForSeconds(wait);
isReloading = false;
}
//function to grenade
IEnumerator COGrenade()
{
//sets Weapon to 0 first to reset
animator.SetBool("Grenade", true);
yield return null;
animator.SetBool("Grenade", false);
yield return new WaitForSeconds(1);
isGrenading = false;
}
//function to Melee
IEnumerator COMelee()
{
GetComponent<Rigidbody>().velocity = new Vector3(0, 0, 0);
canMove = false;
isMoving = false;
animator.SetTrigger("Melee");
yield return new WaitForSeconds(.7f);
isMelee = false;
canMove = true;
}
IEnumerator COKnockback()
{
StartCoroutine(COPlayOneShot("Knockback"));
return null;
}
public IEnumerator CODazed()
{
StartCoroutine(COPlayOneShot("Dazed"));
Debug.Log("Cant Move");
canMove = false;
canFire = false;
canAim = false;
canJump = false;
GetComponent<Rigidbody>().velocity = new Vector3(0, 0, 0);
yield return new WaitForSeconds(3.0f);
GetComponent<Rigidbody>().velocity = new Vector3(0, 0, 0);
canMove = true;
canFire = true;
canAim = true;
canJump = true;
}
#endregion
#region WeaponSwitching
void WeaponSwitch()
{
weaponType++;
if (weaponType == 1)
{
//enables pistol, disables other weapons
pistol.SetActive(true);
rifle.SetActive(false);
launcher.SetActive(false);
heavy.SetActive(false);
StartCoroutine(COSwitchWeapon("Weapon", 1));
}
if (weaponType == 2)
{
//enables rifle, disables other weapons
pistol.SetActive(false);
rifle.SetActive(true);
launcher.SetActive(false);
heavy.SetActive(false);
StartCoroutine(COSwitchWeapon("Weapon", 2));
}
if (weaponType == 3)
{
//enables launcher, disables other weapons
pistol.SetActive(false);
rifle.SetActive(false);
launcher.SetActive(true);
heavy.SetActive(false);
StartCoroutine(COSwitchWeapon("Weapon", 3));
}
if (weaponType == 4)
{
//enables heavy, disables other weapons
pistol.SetActive(false);
rifle.SetActive(false);
launcher.SetActive(false);
heavy.SetActive(true);
StartCoroutine(COSwitchWeapon("Weapon", 4));
}
if (weaponType == 5)
{
//enables pistol, disables other weapons
pistol.SetActive(true);
rifle.SetActive(false);
launcher.SetActive(false);
heavy.SetActive(false);
StartCoroutine(COSwitchWeapon("Weapon", 1));
weaponType = 1;
}
}
#endregion
}
And finally the elevatorOPen script:
using UnityEngine;
using System.Collections;
public class ElevatorOpen : MonoBehaviour
{
private Animator animator;
public AudioClip ElevatorBing;
void Awake ()
{
animator = GetComponent <Animator>();
}
void OnTriggerEnter (Collider other)
{
if (other.gameObject.tag == "Player") {
animator.SetInteger ("Open", 1);
GetComponent<AudioSource>().PlayOneShot(ElevatorBing);
}
}
void OnTriggerExit (Collider other)
{
if (other.gameObject.tag == "Player") {
animator.SetInteger ("Open", 0);
SoldierController.dontMove = true;
}
}
}
This has been addressed. This is a bug with Unity 5 Beta - Spoke to a member of staff who provided me the latest version of Unity, which has fixed the issue.

Categories