Why transform.eulerAngles doesn't rotate my player? - c#

i have a little problem with this game i'm working in, the problem is that the player object isn't rotating with the code i'm using, and it used to work before, idk why, it was working well and i tested several times it's very simple here is the code.
Edit. I just posted the all code of the controller
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
private Rigidbody2D rb;
public float speed;
public float runSpeed;
public float jumpForce;
private float moveInput;
private Vector3 rotation;
public bool isGrounded;
private bool isAlsoTrampoline;
public Transform feetPos;
public float checkRadius;
public LayerMask whatIsGround;
private Animator animator;
private float jumpTimeCounter;
public float jumpTime;
private bool isJumping;
private int cState = 1;
private int capsState = 1;
public bool isWalking;
public bool isRunning;
public bool isCrunching;
public bool isSliding;
public bool isGraping;
public Vector3 climbPos;
private PortalDetector portalName;
private Transform otherPortal;
private int colorPortal = 0;
private GameObject otherPortalPos;
private Vector2 currentY,lastY;
private AudioSource audioStep;
private bool amFalling;
public void Step()
{
audioStep.Play();
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.tag == "Trampoline")
{
isAlsoTrampoline = true;
}
if (collision.tag == "Ledge")
{
Debug.Log("Puedo Trepar esto!!??? ");
if (!isGrounded)
{
isGraping = true;
rb.gravityScale = 0;
rb.velocity = new Vector3(0,0,0);
animator.SetBool("isLedge", true);
climbPos = GetComponent<Transform>().position;
Debug.Log("Trepado!!!!!:DDDDD");
}
}
if (collision.tag == "BluePortal")
{
colorPortal = 1;
}
else if (collision.tag == "OrangePortal")
{
colorPortal = 2;
}
if (collision.tag == "Transporter")
{
if (colorPortal == 1)
{
otherPortal = collision.gameObject.transform.GetChild(3);
}
if (colorPortal == 2)
{
otherPortal = collision.gameObject.transform.GetChild(2);
}
otherPortalPos = otherPortal.transform.gameObject;
transform.position = new Vector3(otherPortalPos.transform.position.x, otherPortalPos.transform.position.y, transform.position.z);
rb.velocity = new Vector3(0, 0, 0);
}
}
void BackToIdle()
{
GetComponent<Rigidbody2D>().velocity = new Vector3(climbPos.x+5,climbPos.y,climbPos.z);
GetComponent<Rigidbody2D>().gravityScale = 10;
animator.SetBool("isLedge", false);
isGraping = false;
}
void ClimbingStepOne()
{
GetComponent<Rigidbody2D>().velocity = new Vector3(climbPos.x, climbPos.y + 5, climbPos.z);
}
void Start()
{
portalName = GetComponent<PortalDetector>();
rb = GetComponent<Rigidbody2D>();
animator = GetComponent<Animator>();
audioStep = GetComponent<AudioSource>();
currentY = lastY;
}
// Update is called once per frame
void FixedUpdate()
{
if (isGrounded && !isGraping)
{
if (isWalking)
{
moveInput = Input.GetAxisRaw("Horizontal");
rb.velocity = new Vector2(moveInput * speed, rb.velocity.y);
}
if (isCrunching)
{
moveInput = Input.GetAxisRaw("Horizontal");
rb.velocity = new Vector2(moveInput * (speed - 1), rb.velocity.y);
}
}
if (isRunning && !isCrunching && !isGraping)
{
moveInput = Input.GetAxisRaw("Horizontal");
rb.velocity = new Vector2(moveInput * runSpeed, rb.velocity.y);
}
if (isRunning && isSliding && !isGraping)
{
moveInput = Input.GetAxisRaw("Horizontal");
rb.velocity = new Vector2(moveInput * runSpeed, rb.velocity.y);
}
}
void Update()
{
isGrounded = Physics2D.OverlapCircle(feetPos.position, checkRadius, whatIsGround);
currentY = new Vector2(transform.position.x, transform.position.y);
if (Input.GetKey(KeyCode.UpArrow) && isGraping)
{
animator.SetBool("isClimbing", true);
}
if (!isGrounded && isAlsoTrampoline)
{
animator.SetBool("isFalling", true);
}
else
{
isAlsoTrampoline = false;
animator.SetBool("isFalling", false);
}
if (Input.GetKeyUp(KeyCode.CapsLock) && !isCrunching)
{
capsState *= -1;
if (capsState < 0 && moveInput == 0)
{
isWalking = false;
isRunning = true;
jumpForce = 14f;
}
else if(capsState > 0 && moveInput == 0)
{
isWalking = true;
isRunning = false;
jumpForce = 7f;
}
else if (capsState < 0 && moveInput != 0)
{
isWalking = false;
isRunning = true;
animator.SetBool("isRunning", true);
animator.SetBool("isWalking", false);
jumpForce = 14f;
}
else if (capsState > 0 && moveInput != 0)
{
isWalking = true;
isRunning = false;
animator.SetBool("isRunning", false);
animator.SetBool("isWalking", true);
jumpForce = 7f;
}
}
if (moveInput > 0)
{
transform.eulerAngles = new Vector3(0, 0, 0);
}
else if (moveInput < 0)
{
transform.eulerAngles = new Vector3(0, 180, 0);
}
if (moveInput == 0)
{
animator.SetBool("isWalking", false);
animator.SetBool("isRunning", false);
}
else
{
if (isWalking)
{
animator.SetBool("isWalking", true);
}
if (isRunning)
{
animator.SetBool("isRunning", true);
}
}
if(isGrounded && Input.GetKeyUp(KeyCode.C))
{
cState *= -1;
if (isRunning)
{
if (cState < 0)
{
StartCoroutine (IsSliding());
cState *= -1;
}
else if (cState > 0)
{
StartCoroutine(IsSliding());
cState *= -1;
}
}
else
{
isRunning = false;
isWalking = true;
if (cState < 0)
{
animator.SetBool("isCrunching", true);
isCrunching = true;
}
else if (cState > 0)
{
animator.SetBool("isCrunching", false);
isCrunching = false;
}
}
}
if (isGrounded && Input.GetKeyDown(KeyCode.Space))
{
isJumping = true;
jumpTimeCounter = jumpTime;
rb.velocity = Vector2.up * jumpForce;
animator.SetTrigger("takeOf");
}
if (isGrounded)
{
animator.SetBool("onGround", true);
animator.SetBool("isFalling", false);
amFalling = false;
}
else
{
if ((currentY.y < lastY.y - 2) && amFalling == false)
{
lastY = currentY;
animator.SetBool("isFalling", true);
amFalling = true;
}
animator.SetBool("onGround", false);
}
if (Input.GetKey(KeyCode.Space) && isJumping == true)
{
if (jumpTimeCounter > 0)
{
rb.velocity = Vector2.up * jumpForce;
jumpTimeCounter -= Time.deltaTime;
}
else
isJumping = false;
}
if (Input.GetKeyUp(KeyCode.Space))
{
isJumping = false;
}
}
IEnumerator IsSliding()
{
isSliding = true;
isRunning = true;
isWalking = false;
animator.SetBool("isCrunching", true);
yield return new WaitForSecondsRealtime(.5f);
animator.SetBool("isCrunching", false);
animator.SetBool("isRunning", true);
isSliding = false;
}
}
i just made a debug.log and this is the result
Move Input Val:1 Moving right, eulerAngle:(0.0, 0.0, 0.0)rotation:(0.0, 0.0, 0.0, 1.0)
UnityEngine.Debug:Log(Object)
PlayerController:Update() (at Assets/Scripts/PlayerController.cs:210)
Move Input Val:-1 Moving left, eulerAngle: (0.0, 180.0, 0.0)rotation:(0.0, 1.0, 0.0, 0.0)
UnityEngine.Debug:Log(Object)
PlayerController:Update() (at Assets/Scripts/PlayerController.cs:215)

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

Why does my dash only function properly if you aren't moving?

Here is the complete player controller file.
using UnityEngine;
public class PlayerCont : MonoBehaviour
{
[Header("Movement Variables")]
public float moveSpeed;
private float speed;
public float maxSpeed;
public float acceleration;
public float dropSpeed;
public float slideSpeed;
public int direction = 1;
[Header("Jump Variables")]
public float jumpForce;
public int extraJumps;
private float jumpTimeCounter;
public float jumpTime;
private bool isJumping;
private int jumpNum;
[Header("Dash Variables")]
public float dashSpeed;
public float dashLength = .5f;
public float dashCooldown = 1f;
private float dashCounter;
public float dashCoolCounter;
private KeyCode _lastKeyCode;
private float doubleTapTime = 0.05f;
private bool doubleTap;
public bool isDashing;
public float dashTime;
public float maxDashTime;
[Header("GroundCheck Variables")]
public Transform groundCheck;
public float checkRadius;
public LayerMask whatIsGround;
[Header("Debug Variables")]
public Rigidbody2D rb;
public float moveInputX;
public float moveInputY;
public bool facingRight = true;
public bool isGrounded;
public bool downKey;
public float rbxVel;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody2D>();
speed = moveSpeed;
jumpNum = extraJumps;
}
void FixedUpdate()
{
}
// Update is called once per frame
void Update()
{
moveInputX = Input.GetAxisRaw("Horizontal");
moveInputY = Input.GetAxisRaw("Vertical");
isGrounded = Physics2D.OverlapCircle(groundCheck.position, checkRadius, whatIsGround);
KeyChecks();
Jump();
GroundPound();
Move();
Dash();
}
void KeyChecks()
{
//restricts movement in Y to only be downward
if (moveInputY > 0)
{
moveInputY = 0;
}
//checks for player drop
if (!isGrounded && moveInputY < 0)
{
downKey = true;
}
else
{
downKey = false;
}
//changes direction relative to keypress
if (Input.GetKeyDown(KeyCode.A))
{
direction = -1;
}
if (Input.GetKeyDown(KeyCode.D))
{
direction = 1;
}
}
void Jump()
{
//sets jump number to user specified amount after touching ground
if (isGrounded)
{
extraJumps = jumpNum;
}
//jumps and decrements extrajumps by 1
if (Input.GetKeyDown(KeyCode.Space) && !downKey && extraJumps > 0)
{
isJumping = true;
rb.velocity = new Vector2(rb.velocity.x, jumpForce);
extraJumps--;
}
//basic jump off of ground
else if (Input.GetKeyDown(KeyCode.Space) && extraJumps == 0 && isGrounded && !downKey)
{
isJumping = true;
rb.velocity = new Vector2(rb.velocity.x, jumpForce);
}
//checks for longkeypress of spacebar and increases length of jump
if (Input.GetKey(KeyCode.Space) && extraJumps > 1 && isJumping) // allows a hold down increase to jump while grounded
{
if (jumpTimeCounter > 0)
{
rb.velocity = new Vector2(rb.velocity.x, jumpForce);
jumpTimeCounter -= Time.deltaTime;
}
else
{
jumpTimeCounter = jumpTime;
isJumping = false;
}
}
}
void GroundPound()
{
//ground pound keypress check
if (!isGrounded && Input.GetKeyDown(KeyCode.S))
{
if (!doubleTap && doubleTapTime > Time.time && _lastKeyCode == KeyCode.S)
{
rb.velocity = new Vector2(rb.velocity.x, -1 * dropSpeed);
Debug.Log("dashing right");
}
else
{
doubleTapTime = Time.time + 0.5f;
}
_lastKeyCode = KeyCode.S;
}
}
void Move()
{
//changes movement relative to input
if (!isDashing)
{
if (isGrounded && Input.GetKey(KeyCode.S))
{
rb.velocity = new Vector2(rb.velocity.x * .999f, rb.velocity.y);
}
else if (moveInputX == 0 && isGrounded)
{
speed = moveSpeed;
rb.velocity = new Vector2(rb.velocity.x * .99f, rb.velocity.y);
}
else if (moveInputX == 0 && !isGrounded)
{
speed = moveSpeed;
}
else
{
rb.velocity = new Vector2(moveInputX * speed, moveInputY / 10 + rb.velocity.y);
}
}
//checks player velocity
rbxVel = rb.velocity.x;
//increases speed relative to input direction
if (moveInputX > 0 || moveInputX < 0)
{
speed += acceleration;
}
//caps speed
if (speed > maxSpeed)
{
speed = maxSpeed;
}
//caps min speed
if (speed < moveSpeed)
{
speed = moveSpeed;
}
}
void Dash()
{
if (Input.GetKeyDown(KeyCode.LeftShift))
{
isDashing = true;
if (isDashing && dashCoolCounter <= 0)
{
dashTime -= Time.deltaTime;
dashCoolCounter = dashCooldown;
rb.velocity = new Vector2(dashSpeed * direction, rb.velocity.y);
Debug.Log("Dash Started");
}
}
else
{
dashTime = maxDashTime;
isDashing = false;
Debug.Log("No Dash");
}
//resets dash cooldown
if (dashCoolCounter > 0)
{
dashCoolCounter -= Time.deltaTime;
}
}
void Flip()
{
facingRight = !facingRight;
Vector3 Scaler = transform.localScale;
Scaler.x *= -1;
transform.localScale = Scaler;
}
}
When using the keys for movement (A, S) the dash doesn't function. Oddly enough the code is executing (I see my debug statement in console) but nothing physically changes.
When rewriting the code for the dash from: rb.velocity = new Vector2(dashSpeed * direction, rb.velocity.y) to: rb.velocity = dashspeed the dash will work without issue. The only downside to that is that the Y component of the RigidBody is being manipulated as well.
This has been an issue for days now, and I am just rewriting the post.
Any and all help is welcomed.
You're setting isDashing = false too soon. It gets set to false as soon as you let go of Shift which allows Move to execute its code and change your rigidbody's velocity back to normal move.
Didn't test this, but give it a shot and see if it works the way you want it to.
void Dash()
{
if (Input.GetKeyDown(KeyCode.LeftShift))
{
if (!isDashing && dashCoolCounter <= 0)
{
isDashing = true;
dashTime = 0;
dashCoolCounter = dashCooldown;
rb.velocity = new Vector2(dashSpeed * direction, rb.velocity.y);
Debug.Log("Dash Started");
}
else if(isDashing)
{
rb.velocity = new Vector2(dashSpeed * direction, rb.velocity.y);
dashTime += Time.deltaTime;
if(dashTime >= maxDashTime)
{
isDashing = false;
Debug.Log("No Dash");
}
}
}
// resets dash cooldown
if (dashCoolCounter > 0)
{
dashCoolCounter -= Time.deltaTime;
}
}

Unity Multiplayer sending position and update to partner, socket.io

I'm trying to make a 2D multiplayer game and I encountered the next problem: animation and movement are not displayed correctely to partner. They have a small delay and the character looks judder. My annimation has 3 states: (IDLE, MOVE AND JUMP).Both objects have rigidbody component - player1,player 2. My code looks like this:
Sending position from player 1 to player 2: GameController.cs
public PlayerManager player1;
public PartenerManager player2;
void Update () // CODE TO SEND POSITION
{
if (player1.transform.position.x!=position.x || player1.transform.position.y!=position.y || player1.transform.position.z !=position.z)
{
int state = player1.getState();
position = new Vector3(player1.transform.position.x, player1.transform.position.y, player1.transform.position.z);
Dictionary<string, string> data = new Dictionary<string, string>();
data["position"] = position.x + ";" + position.y + ";" + position.z;
data["state"] = state.ToString(); // this is for the state of the annimation
socket.Emit("MOVE", new JSONObject(data));
}
}
// RECEIVING POSITION
void Start () {
socket.On("MOVED", onUserMove);
}
void onUserMove(SocketIOEvent obj)
{
string stare = obj.data.GetField("state").ToString();
stare = stare.Substring(1);
stare = stare.Substring(0, stare.Length - 1);
player2.setPositionState(JsonToVector3(JsonToString(obj.data.GetField("position").ToString(),"\"")),int.Parse(stare));
}
Recieveing and displaying the position at player 2: PartnerManager.cs
public class PartenerManager : MonoBehaviour {
public bool gotmove=false;
public float speedX = 6;
private string playerName;
public Text username;
Animator anim;
Rigidbody2D rb;
bool facingRight;
float speed;
Vector3 vec3;
int stare;
void Start () {
rb = GetComponent<Rigidbody2D>();
anim = GetComponent<Animator>();
facingRight = true;
}
void Flip()
{
if ((speed> 0 && !facingRight) || (speed < 0 && facingRight))
{
facingRight = !facingRight;
Vector3 temp = transform.localScale;
temp.x *= -1;
transform.localScale = temp;
}
}
public void setPositionState(Vector3 ve,int st)
{
gotmove = true;
vec3 = ve;
stare = st;
}
void FixedUpdate ()
{
if (gotmove==true)
{
if (transform.position.x < vec3.x)
{
Debug.Log("RIGHT");
speed = speedX;
}
if (transform.position.x > vec3.x)
{
Debug.Log("Left");
speed= -speedX;
}
if (transform.position.x == vec3.x)
{
speed = 0;
}
transform.position = vec3;
Flip();
anim.SetInteger("State", stare);
gotmove = false;
}
}
}
Player 1 code: PlayerManager.cs
public class PlayerManager : MonoBehaviour {
public float speedX=6;
public float jumpSpeedY=300;
private string playerName;
public Text username;
Animator anim;
Rigidbody2D rb;
bool facingRight;
bool jumping;
bool grounded;
float speed;
int numJumps = 0;
void Start ()
{
anim = GetComponent<Animator>();
rb = GetComponent<Rigidbody2D>();
facingRight = true;
grounded = false;
}
public int getState()
{
return anim.GetInteger("State");
}
void Update ()
{
MovePlayer(speed);
Flip();
}
void MovePlayer(float playerSpeed)
{
if ((playerSpeed < 0 && !jumping) || (playerSpeed>0 && !jumping))
{
anim.SetInteger("State", 1);
}
if(playerSpeed==0 && !jumping)
{
anim.SetInteger("State", 0);
}
rb.velocity = new Vector3(speed, rb.velocity.y, 0);
}
void Flip()
{
if((speed>0 && !facingRight) || (speed<0 && facingRight))
{
facingRight = !facingRight;
Vector3 temp = transform.localScale;
temp.x *= -1;
transform.localScale = temp;
}
}
void OnCollisionEnter2D(Collision2D other)
{
if(other.gameObject.tag=="ground")
{
jumping = false;
numJumps = 0;
grounded = true;
anim.SetInteger("State", 0);
}
}
public void WalkLeft()
{
speed = -speedX;
}
public void WalkRight()
{
speed = speedX;
}
public void StopMoving()
{
speed = 0;
}
public void Jump()
{
grounded = false;
if (grounded == true && numJumps >= 2)
{
numJumps = 0;
}
if (numJumps < 2 )
{
jumping = true;
if (numJumps == 0)
{
rb.AddForce(new Vector2(rb.velocity.x, jumpSpeedY));
}
else
{
rb.AddForce(new Vector2(rb.velocity.x, jumpSpeedY-100));
}
anim.SetInteger("State", 2);
numJumps++;
}
}
}
I resolved the problem. When you send the position you have also to send the rotation - quaternion . Here is my solution:
IMPORTANT: in the rigidbodycomponent, the z ax rotation must be checked
PartnerManager.cs - partner. The object that have to be sync
public class PartenerManager : MonoBehaviour
public Text username;
Vector3 targetPosition;
Quaternion targetRotation;
Animator anim;
bool facingRight;
int state;
void Start()
{
anim = GetComponent<Animator>();
facingRight = true;
anim.SetInteger("State", 0);
}
void Flip()
{
facingRight = !facingRight;
Vector3 temp = transform.localScale;
temp.x *= -1;
transform.localScale = temp;
}
public void setPositionState(Vector3 pozitie, Quaternion rotatie, int stare)
{
targetPosition = pozitie;
targetRotation = rotatie;
state = stare;
}
void ApplyMovement()
{
Debug.Log("pozitie actuala:" + transform.position.x + " pozitie mutata: " + targetPosition.x);
if (transform.position.x < targetPosition.x)
{
if (facingRight != true)
{
Flip();
facingRight = true;
}
}
if (transform.position.x > targetPosition.x)
{
if (facingRight == true)
{
Flip();
facingRight = false;
}
}
transform.position = Vector3.Lerp(transform.position, targetPosition, 0.5f);
transform.rotation = Quaternion.Lerp(transform.rotation, targetRotation, 0.5f);
anim.SetInteger("State", state);
}
void FixedUpdate()
{
ApplyMovement();
}
GameController.cs - the controlloer. Here i send and receive the message with the position
if (player1.transform.position.x != position.x || player1.transform.position.y != position.y || player1.transform.position.z != position.z)
{
int state = player1.getState();
position = new Vector3(player1.transform.position.x, player1.transform.position.y, player1.transform.position.z);
Dictionary<string, string> data = new Dictionary<string, string>();
data["position"] = position.x + ";" + position.y + ";" + position.z;
data["state"] = state.ToString();
data["rotation"] = player1.transform.rotation.x + ";" + player1.transform.rotation.y + ";" + player1.transform.rotation.z + ";" + player1.transform.rotation.w;
socket.Emit("MOVE", new JSONObject(data));
}
Quaternion JsonToQuaternion(string target)
{
Quaternion newVector;
string[] newString = Regex.Split(target, ";");
newVector = new Quaternion(float.Parse(newString[0]), float.Parse(newString[1]), float.Parse(newString[2]),float.Parse(newString[3]));
return newVector;
}
void onUserMove(SocketIOEvent obj)
{
string stare = obj.data.GetField("state").ToString();
stare = stare.Substring(1);
stare = stare.Substring(0, stare.Length - 1);
Vector3 pozitie = JsonToVector3(JsonToString(obj.data.GetField("position").ToString(), "\""));
Quaternion rotatie= JsonToQuaternion(JsonToString(obj.data.GetField("rotation").ToString(), "\""));
int state = int.Parse(stare);
//Debug.Log("Partener: pozitie: " + pozitie + " rotatie " + rotatie + " stare: " + stare);
player2.setPositionState(pozitie,rotatie,state);
//player2.setPositionState(JsonToVector3(JsonToString(obj.data.GetField("position").ToString(),"\"")),int.Parse(stare));
}

move a gameobject position in a slow motion unity c#

I wanna move the Camera (GameObject) to be like navigating between panels... Its working well but I want it to be in a slow motion to be like animation. I am using unity and c#.
Thank you for your help
public class moveCanvas : MonoBehaviour
{
Vector3 reset = new Vector3(0, 0, -10);
Vector3 leftpanel = new Vector3(-205.5f, 0, 0);
Vector3 rightpanel = new Vector3(205.5f, 0, 0);
void Update()
{
if (Input.GetKeyDown(KeyCode.A))
{
GoLeft();
}
if (Input.GetKeyDown(KeyCode.D))
{
GoRight();
}
}
public void GoLeft()
{
Vector3 currentposition = GameObject.Find("Main Camera").transform.position;
if (currentposition == reset)
GameObject.Find("Main Camera").transform.position = leftpanel;
else if (currentposition == rightpanel)
GameObject.Find("Main Camera").transform.position = reset;
else
return;
}
public void GoRight()
{
Vector3 currentposition = GameObject.Find("Main Camera").transform.position;
if (currentposition == reset)
GameObject.Find("Main Camera").transform.position = rightpanel;
else if (currentposition == leftpanel)
GameObject.Find("Main Camera").transform.position = reset;
else
return;
}
I Found the answer
using System.Collections;
using UnityEngine;
public class MoveCanvas : MonoBehaviour
{
private Vector3 _reset = new Vector3(0, 0, -10);
private Vector3 _leftpanel = new Vector3(-205.5f, 0, 0);
private Vector3 _rightpanel = new Vector3(205.5f, 0, 0);
private float _smoothTime = 0.7f;
private Vector3 _velocity = Vector3.zero;
private Vector3 _currentposition;
private int _stoplimit = 2;
void Start()
{
_currentposition = gameObject.transform.position;
}
void Update()
{
if (Input.GetKeyDown(KeyCode.A))
{
StartCoroutine(GoLeft());
}
else if (Input.GetKeyDown(KeyCode.D))
{
StartCoroutine(GoRight());
}
}
private IEnumerator GoLeft()
{
if (_currentposition == _reset)
{
while (!Mathf.Approximately(_currentposition.x, _leftpanel.x))
{
gameObject.transform.position = Vector3.SmoothDamp(_currentposition, _leftpanel, ref _velocity, _smoothTime);
_currentposition = gameObject.transform.position;
if (Mathf.Abs((_currentposition.x) - (_leftpanel.x)) < _stoplimit)
{
break;
}
yield return new WaitForEndOfFrame();
}
gameObject.transform.position = _leftpanel;
_currentposition = _leftpanel;
}
else if (_currentposition == _rightpanel)
{
while (!Mathf.Approximately(_currentposition.x, _reset.x))
{
gameObject.transform.position = Vector3.SmoothDamp(_currentposition, _reset, ref _velocity, _smoothTime);
_currentposition = gameObject.transform.position;
if (Mathf.Abs((_currentposition.x) - (_reset.x)) < _stoplimit)
{
break;
}
yield return new WaitForEndOfFrame();
}
gameObject.transform.position = _reset;
_currentposition = _reset;
}
}
private IEnumerator GoRight()
{
if (_currentposition == _reset)
{
while (!Mathf.Approximately(_currentposition.x, _rightpanel.x))
{
gameObject.transform.position = Vector3.SmoothDamp(_currentposition, _rightpanel, ref _velocity, _smoothTime);
_currentposition = gameObject.transform.position;
if (Mathf.Abs((_currentposition.x) - (_rightpanel.x)) < _stoplimit)
{
break;
}
yield return new WaitForEndOfFrame();
}
gameObject.transform.position = _rightpanel;
_currentposition = _rightpanel;
}
else if (_currentposition == _leftpanel)
{
while (!Mathf.Approximately(_currentposition.x, _reset.x))
{
gameObject.transform.position = Vector3.SmoothDamp(_currentposition, _reset, ref _velocity, _smoothTime);
_currentposition = gameObject.transform.position;
if (Mathf.Abs((_currentposition.x) - (_reset.x)) < _stoplimit)
{
break;
}
yield return new WaitForEndOfFrame();
}
gameObject.transform.position = _reset;
_currentposition = _reset;
}
}
}

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