I am using Photon PUN 2 for multiplayer in Unity.
I can create a room or join a room.
The problem appears when I join with a second player. When I control one of the players, I control the other player instead.
I am using Standard Assets FPS controller.
Do anyone know what is causing the problem?
Any help would be appreciated.
I will share the edited code:
using System;
using UnityEngine;
using UnityStandardAssets.CrossPlatformInput;
using UnityStandardAssets.Utility;
using Random = UnityEngine.Random;
using Photon.Pun;
#pragma warning disable 618, 649
namespace UnityStandardAssets.Characters.FirstPerson
{
[RequireComponent(typeof (CharacterController))]
[RequireComponent(typeof (AudioSource))]
public class FirstPersonController : MonoBehaviour
{
[SerializeField] private bool m_IsWalking;
[SerializeField] private float m_WalkSpeed;
[SerializeField] private float m_RunSpeed;
[SerializeField] [Range(0f, 1f)] private float m_RunstepLenghten;
[SerializeField] private float m_JumpSpeed;
[SerializeField] private float m_StickToGroundForce;
[SerializeField] private float m_GravityMultiplier;
[SerializeField] private MouseLook m_MouseLook;
[SerializeField] private bool m_UseFovKick;
[SerializeField] private FOVKick m_FovKick = new FOVKick();
[SerializeField] private bool m_UseHeadBob;
[SerializeField] private CurveControlledBob m_HeadBob = new CurveControlledBob();
[SerializeField] private LerpControlledBob m_JumpBob = new LerpControlledBob();
[SerializeField] private float m_StepInterval;
[SerializeField] private AudioClip[] m_FootstepSounds; // an array of footstep sounds that will be randomly selected from.
[SerializeField] private AudioClip m_JumpSound; // the sound played when character leaves the ground.
[SerializeField] private AudioClip m_LandSound; // the sound played when character touches back on ground.
PhotonView view;
private Camera m_Camera;
private bool m_Jump;
private float m_YRotation;
private Vector2 m_Input;
private Vector3 m_MoveDir = Vector3.zero;
private CharacterController m_CharacterController;
private CollisionFlags m_CollisionFlags;
private bool m_PreviouslyGrounded;
private Vector3 m_OriginalCameraPosition;
private float m_StepCycle;
private float m_NextStep;
private bool m_Jumping;
private AudioSource m_AudioSource;
// Use this for initialization
private void Start()
{
m_CharacterController = GetComponent<CharacterController>();
m_Camera = Camera.main;
m_OriginalCameraPosition = m_Camera.transform.localPosition;
m_FovKick.Setup(m_Camera);
m_HeadBob.Setup(m_Camera, m_StepInterval);
m_StepCycle = 0f;
m_NextStep = m_StepCycle/2f;
m_Jumping = false;
m_AudioSource = GetComponent<AudioSource>();
m_MouseLook.Init(transform , m_Camera.transform);
view = GetComponent<PhotonView>();
}
// Update is called once per frame
private void Update()
{
RotateView();
// the jump state needs to read here to make sure it is not missed
if (!m_Jump)
{
m_Jump = CrossPlatformInputManager.GetButtonDown("Jump");
}
if (!m_PreviouslyGrounded && m_CharacterController.isGrounded)
{
StartCoroutine(m_JumpBob.DoBobCycle());
PlayLandingSound();
m_MoveDir.y = 0f;
m_Jumping = false;
}
if (!m_CharacterController.isGrounded && !m_Jumping && m_PreviouslyGrounded)
{
m_MoveDir.y = 0f;
}
m_PreviouslyGrounded = m_CharacterController.isGrounded;
}
private void PlayLandingSound()
{
m_AudioSource.clip = m_LandSound;
m_AudioSource.Play();
m_NextStep = m_StepCycle + .5f;
}
private void FixedUpdate()
{
if (view.IsMine)
{
float speed;
GetInput(out speed);
// always move along the camera forward as it is the direction that it being aimed at
Vector3 desiredMove = transform.forward * m_Input.y + transform.right * m_Input.x;
// get a normal for the surface that is being touched to move along it
RaycastHit hitInfo;
Physics.SphereCast(transform.position, m_CharacterController.radius, Vector3.down, out hitInfo,
m_CharacterController.height / 2f, Physics.AllLayers, QueryTriggerInteraction.Ignore);
desiredMove = Vector3.ProjectOnPlane(desiredMove, hitInfo.normal).normalized;
m_MoveDir.x = desiredMove.x * speed;
m_MoveDir.z = desiredMove.z * speed;
if (m_CharacterController.isGrounded)
{
m_MoveDir.y = -m_StickToGroundForce;
if (m_Jump)
{
m_MoveDir.y = m_JumpSpeed;
PlayJumpSound();
m_Jump = false;
m_Jumping = true;
}
}
else
{
m_MoveDir += Physics.gravity * m_GravityMultiplier * Time.fixedDeltaTime;
}
m_CollisionFlags = m_CharacterController.Move(m_MoveDir * Time.fixedDeltaTime);
ProgressStepCycle(speed);
UpdateCameraPosition(speed);
m_MouseLook.UpdateCursorLock();
}
}
private void PlayJumpSound()
{
m_AudioSource.clip = m_JumpSound;
m_AudioSource.Play();
}
private void ProgressStepCycle(float speed)
{
if (m_CharacterController.velocity.sqrMagnitude > 0 && (m_Input.x != 0 || m_Input.y != 0))
{
m_StepCycle += (m_CharacterController.velocity.magnitude + (speed*(m_IsWalking ? 1f : m_RunstepLenghten)))*
Time.fixedDeltaTime;
}
if (!(m_StepCycle > m_NextStep))
{
return;
}
m_NextStep = m_StepCycle + m_StepInterval;
PlayFootStepAudio();
}
private void PlayFootStepAudio()
{
if (!m_CharacterController.isGrounded)
{
return;
}
// pick & play a random footstep sound from the array,
// excluding sound at index 0
int n = Random.Range(1, m_FootstepSounds.Length);
m_AudioSource.clip = m_FootstepSounds[n];
m_AudioSource.PlayOneShot(m_AudioSource.clip);
// move picked sound to index 0 so it's not picked next time
m_FootstepSounds[n] = m_FootstepSounds[0];
m_FootstepSounds[0] = m_AudioSource.clip;
}
private void UpdateCameraPosition(float speed)
{
if (view.IsMine)
{
Vector3 newCameraPosition;
if (!m_UseHeadBob)
{
return;
}
if (m_CharacterController.velocity.magnitude > 0 && m_CharacterController.isGrounded)
{
m_Camera.transform.localPosition =
m_HeadBob.DoHeadBob(m_CharacterController.velocity.magnitude +
(speed * (m_IsWalking ? 1f : m_RunstepLenghten)));
newCameraPosition = m_Camera.transform.localPosition;
newCameraPosition.y = m_Camera.transform.localPosition.y - m_JumpBob.Offset();
}
else
{
newCameraPosition = m_Camera.transform.localPosition;
newCameraPosition.y = m_OriginalCameraPosition.y - m_JumpBob.Offset();
}
m_Camera.transform.localPosition = newCameraPosition;
}
}
private void GetInput(out float speed)
{
// Read input
float horizontal = CrossPlatformInputManager.GetAxis("Horizontal");
float vertical = CrossPlatformInputManager.GetAxis("Vertical");
bool waswalking = m_IsWalking;
#if !MOBILE_INPUT
// On standalone builds, walk/run speed is modified by a key press.
// keep track of whether or not the character is walking or running
m_IsWalking = !Input.GetKey(KeyCode.LeftShift);
#endif
// set the desired speed to be walking or running
speed = m_IsWalking ? m_WalkSpeed : m_RunSpeed;
m_Input = new Vector2(horizontal, vertical);
// normalize input if it exceeds 1 in combined length:
if (m_Input.sqrMagnitude > 1)
{
m_Input.Normalize();
}
// handle speed change to give an fov kick
// only if the player is going to a run, is running and the fovkick is to be used
if (m_IsWalking != waswalking && m_UseFovKick && m_CharacterController.velocity.sqrMagnitude > 0)
{
StopAllCoroutines();
StartCoroutine(!m_IsWalking ? m_FovKick.FOVKickUp() : m_FovKick.FOVKickDown());
}
}
private void RotateView()
{
if (view.IsMine)
{
m_MouseLook.LookRotation(transform, m_Camera.transform);
}
}
private void OnControllerColliderHit(ControllerColliderHit hit)
{
Rigidbody body = hit.collider.attachedRigidbody;
//dont move the rigidbody if the character is on top of it
if (m_CollisionFlags == CollisionFlags.Below)
{
return;
}
if (body == null || body.isKinematic)
{
return;
}
body.AddForceAtPosition(m_CharacterController.velocity*0.1f, hit.point, ForceMode.Impulse);
}
}
}
put isMine in your code and put the movement code inside of it
Example:
private void Update()
{
if(view.IsMine){ //Add this
RotateView();
if (!m_Jump)
{
m_Jump = CrossPlatformInputManager.GetButtonDown("Jump");
}
if (!m_PreviouslyGrounded && m_CharacterController.isGrounded)
{
StartCoroutine(m_JumpBob.DoBobCycle());
PlayLandingSound();
m_MoveDir.y = 0f;
m_Jumping = false;
}
if (!m_CharacterController.isGrounded && !m_Jumping && m_PreviouslyGrounded)
{
m_MoveDir.y = 0f;
}
m_PreviouslyGrounded = m_CharacterController.isGrounded;
}
}
Related
I have a script that detect when player is touching a layer named "Ground", and it works pretty well, but my problem is when I use the "Platform Effector 2D" that allows me jump through the plataform. So, when my character is passsing through the plataform, my bool "isGrounded" gets true, but he is actually not in ground, what happens is that the point that I use to check is "colliding" with the object that countains the layer Ground.
I don't think I can explain it very well, so I upload a not listed video on Youtube to show
www.youtube.com/watch?v=EQpF4iSNC0Yt
here's the code
[Header("Components")]
[HideInInspector]public Rigidbody2D _rb;
[Header("Layer Masks")]
[SerializeField] private LayerMask groundLayer;
[Header("Movement Variables")]
[SerializeField] private float _movementAcceleration;
[SerializeField] private float _maxMoveSpeed;
[SerializeField] private float _linearDrag;
[SerializeField] private float dashPower;
private float horizontalDirection;
private bool changingDirection => (_rb.velocity.x > 0f && horizontalDirection < 0f) || (_rb.velocity.x < 0f && horizontalDirection > 0f);
public bool isFalling => _rb.velocity.y < 0.0f;
private bool isRunning => horizontalDirection != 0;
[Header("Jump Variables")]
[SerializeField] private float jumpForce = 12f;
[SerializeField] private float airLinearDrag = 2.5f;
[SerializeField] private float fallMultiplier = 8f;
[SerializeField] private float lowJumpFallMultiplier = 5f;
private bool canJump => Input.GetButtonDown("Jump") && isGround;
[Header("Ground Colission Variables")]
[SerializeField] private float groundRayCastLenght;
private bool isGround;
private bool jumped;
private bool facinRight = true;
private Animator animator;
private SpriteRenderer sprite;
GameController controller;
public Transform groundCheck ;
public bool canPassThrough = false;
void Start()
{
sprite = GetComponent<SpriteRenderer>();
animator = GetComponent<Animator>();
_rb = GetComponent<Rigidbody2D>();
controller = FindObjectOfType<GameController>();
}
// Update is called once per frame
void Update()
{
Debug.Log(_rb.velocity.y);
isGround = Physics2D.Linecast(transform.position, groundCheck.position, 1 << LayerMask.NameToLayer("Ground"));
horizontalDirection = GetInput().x;
if(canJump && !controller.gamePaused){
Jump();
}
if(Input.GetKeyDown(KeyCode.LeftShift)){
ApplyDash();
}
setAnimations();
}
void FixedUpdate()
{
//CheckCollisions();
if(!controller.gamePaused){
//checkDirection();
MoveCharacter();
}
if(isGround){
jumped = false;
ApplyLinearDrag();
}else{
ApplyAirLinearDrag();
FallMultiplier();
}
}
private Vector2 GetInput()
{
return new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
}
private void MoveCharacter(){
if(horizontalDirection < 0 && facinRight || horizontalDirection > 0 && !facinRight){
checkDirection();
}
Vector3 v = _rb.velocity;
_rb.AddForce(new Vector2(horizontalDirection* _movementAcceleration, 0f) );
if(Mathf.Abs(_rb.velocity.x) > _maxMoveSpeed){
v.x = Mathf.Sign(_rb.velocity.x) * _maxMoveSpeed;
_rb.velocity = v;
//_rb.velocity = new Vector2(Mathf.Sign(_rb.velocity.x) * _maxMoveSpeed, _rb.velocity.y );
}
}
private void CheckCollisions(){
isGround = Physics2D.Raycast(transform.position * groundRayCastLenght, Vector2.down, groundRayCastLenght, groundLayer);
}
private void ApplyLinearDrag(){
if(Mathf.Abs(horizontalDirection) < 0.4f || changingDirection){
_rb.drag = _linearDrag;
}else{
_rb.drag = 0f;
}
}
private void ApplyDash(){
_rb.AddForce(new Vector2(horizontalDirection * dashPower, _rb.velocity.y));
}
void ApplyAirLinearDrag(){
_rb.drag = airLinearDrag;
}
void Jump(){
jumped = true;
if(horizontalDirection != 0){
_rb.velocity = new Vector2(_rb.velocity.x, 0f);
_rb.AddForce(Vector2.up * jumpForce, ForceMode2D.Impulse);
}else{
_rb.velocity = new Vector2(_rb.velocity.x, 0f);
_rb.AddForce(Vector2.up * jumpForce * 2f, ForceMode2D.Impulse);
}
}
void OnDrawGizmos()
{
Gizmos.color = Color.green;
Gizmos.DrawLine(transform.position, transform.position + Vector3.down * groundRayCastLenght);
}
void FallMultiplier(){
if(_rb.velocity.y < 0){
_rb.gravityScale = fallMultiplier;
}else if(_rb.velocity.y > 0 && !Input.GetButtonDown("Jump")){
_rb.gravityScale = lowJumpFallMultiplier;
}else{
_rb.gravityScale = 1f;
}
}
void setAnimations(){
animator.SetBool("Run", isRunning && isGround);
animator.SetBool("isGround", isGround);
animator.SetBool("Jump", jumped);
animator.SetBool("isFalling", isFalling);
animator.SetFloat("eixoY", Mathf.Abs(_rb.velocity.y));
}
void checkDirection(){
facinRight = !facinRight;
transform.localScale = new Vector3( - transform.localScale.x, transform.localScale.y, transform.localScale.z);
}
void OnCollisionEnter2D(Collision2D other)
{
if(LayerMask.LayerToName(other.gameObject.layer) == "Ground") //check layer is ground
{
if (gameObject.GetComponent<Rigidbody2D>().velocity.y <= 0) //check velocity.y is 0
{
Debug.Log("in ground"); //debug console
canPassThrough = false;
}else{
Debug.Log("Not in ground");
canPassThrough = true;
}
}
}
If we want to perform the debug operation when we touch it, we can perform the operation successfully by checking that the velocity.y is 0 at the moment it touches.
like this:
private void OnCollisionEnter2D(Collision2D collision)
{
if(LayerMask.LayerToName(collision.gameObject.layer) == "Ground") //check layer is ground
{
if (gameObject.GetComponent<Rigidbody2D>().velocity.y <= 0) //check velocity.y is 0
{
Debug.Log("in ground"); //debug console
}
}
}
So, when I start the game, my character can jump on the first platform (because that is the manually placed platform), but I cannot jump on the spawned floors. BTW I am able to run on the floors and I know my jump works correctly.
I have tried so many ways of collider detection I am going crazy and I know its a simple fix that I just can't figure out.
I expected my character to be able to jump on the duplicated platforms but the character just doesn't do anything at all.
If anyone is willing to take a look that would be very helpful. - Nick
P.S I know my code is messy.
CODE:
#Code that is on my player script#
using System;
using System.Diagnostics;
using System.Threading;
using System.Collections;
using System.Collections.Generic;
using TouchControlsKit;
using UnityEngine;
using UnityEngine.SceneManagement;
using System.Text;
using System.IO;
public class Attack : MonoBehaviour
{
const float k_GroundedRadius = .2f; // Radius of the overlap circle to determine if grounded
[SerializeField] private LayerMask m_WhatIsGround;
[SerializeField] private Transform m_GroundCheck;
private bool m_Grounded;
public Collider2D objectCollider;
public Collider2D anotherCollider;
[Range(0, .3f)] [SerializeField] private float m_MovementSmoothing = .05f;
private Timer t;
private Timer a;
private float timeStamp;
private float die = 0;
public GameObject bullet;
private bool m_FacingRight = true;
public float move;
private Vector3 velocity = Vector3.zero;
public GameObject idle_0;
public playscript play;
public Transform player;
private Rigidbody2D m_Rigidbody2D;
[SerializeField] private float m_JumpForce = 200f;
bool swing = false;
bool isgrounded = false;
public bool canJump = false;
bool slide = false;
public Transform groundLayer; // Insert the layer here.
public Vector2 jumpHeight;
private Vector2 touchOrigin = -Vector2.one;
public Vector2 moveSpeed;
public bool run;
Collider2D m_Collider;
// variable to hold a reference to our SpriteRenderer component
private SpriteRenderer mySpriteRenderer;
// This function is called just one time by Unity the moment the component loads
private void Awake()
{
// get a reference to the SpriteRenderer component on this gameObject
mySpriteRenderer = GetComponent<SpriteRenderer>();
animator.SetBool("death", false);
}
public Animator animator;
Animator anim;
int swingHash = Animator.StringToHash("swing");
// Use this for initialization
void Start()
{
timeStamp = Time.time + 5;
m_Collider = GetComponent<Collider2D>();
run = false;
m_Rigidbody2D = GetComponent<Rigidbody2D>();
anim = GetComponent<Animator>();
animator.SetBool("isgrounded", false);
isgrounded = false;
canJump = false;
animator.SetBool("swing", false);
}
private void FixedUpdate()
{
m_Grounded = false;
// The player is grounded if a circlecast to the groundcheck position hits anything designated as ground
// This can be done using layers instead but Sample Assets will not overwrite your project settings.
Collider2D[] colliders = Physics2D.OverlapCircleAll(m_GroundCheck.position, k_GroundedRadius, m_WhatIsGround);
for (int i = 0; i < colliders.Length; i++)
{
if (colliders[i].gameObject != gameObject)
animator.SetBool("isgrounded", true);
m_Grounded = true;
}
}
// Update is called once per frame
void Update()
{
anotherCollider = GameObject.FindGameObjectWithTag("Ground").GetComponent<BoxCollider2D>();
objectCollider = GameObject.FindGameObjectWithTag("Player").GetComponent<CapsuleCollider2D>();
Vector3 targetVelocity = new Vector2(move * 2f, m_Rigidbody2D.velocity.y);
m_Rigidbody2D.velocity = Vector3.SmoothDamp(m_Rigidbody2D.velocity, targetVelocity, ref velocity, m_MovementSmoothing);
animator.SetBool("run", true);
if (move > 0 && !m_FacingRight)
{
// ... flip the player.
Flip();
}
// Otherwise if the input is moving the player left and the player is facing right...
else if (move < 0 && m_FacingRight)
{
// ... flip the player.
Flip();
}
int horizontal = 0; //Used to store the horizontal move direction.
int vertical = 0; //Used to store the vertical move direction.
#if UNITY_STANDALONE || UNITY_WEBPLAYER
//Check if we are running on iOS, Android, Windows Phone 8 or Unity iPhone
#elif UNITY_IOS || UNITY_ANDROID || UNITY_WP8 || UNITY_IPHONE
//Check if Input has registered more than zero touches
if (Input.touchCount > 0)
{
//Store the first touch detected.
Touch myTouch = Input.touches[0];
//Check if the phase of that touch equals Began
if (myTouch.phase == TouchPhase.Began)
{
//If so, set touchOrigin to the position of that touch
touchOrigin = myTouch.position;
}
//If the touch phase is not Began, and instead is equal to Ended and the x of touchOrigin is greater or equal to zero:
else if (myTouch.phase == TouchPhase.Ended && touchOrigin.x >= 0)
{
//Set touchEnd to equal the position of this touch
Vector2 touchEnd = myTouch.position;
//Calculate the difference between the beginning and end of the touch on the x axis.
float x = touchEnd.x - touchOrigin.x;
//Calculate the difference between the beginning and end of the touch on the y axis.
float y = touchEnd.y - touchOrigin.y;
//Set touchOrigin.x to -1 so that our else if statement will evaluate false and not repeat immediately.
touchOrigin.x = -1;
//Check if the difference along the x axis is greater than the difference along the y axis.
if (Mathf.Abs(x) > Mathf.Abs(y))
//If x is greater than zero, set horizontal to 1, otherwise set it to -1
horizontal = x > 0 ? 1 : -1;
else
//If y is greater than zero, set horizontal to 1, otherwise set it to -1
vertical = y > 0 ? 1 : -1;
}
}
#endif
if (TCKInput.GetAction("jumpBtn", EActionEvent.Up))
{
animator.SetBool("jump", false);
}
if (TCKInput.GetAction("jumpBtn", EActionEvent.Down) && m_Grounded == true)
{
animator.SetBool("jump", true);
m_Grounded = false;
m_Rigidbody2D.AddForce(new Vector2(0f, m_JumpForce));
}
if (TCKInput.GetAction("fireBtn", EActionEvent.Down))
{
animator.SetBool("swing", true);
m_Collider.enabled = !m_Collider.enabled;
}
if (TCKInput.GetAction("fireBtn", EActionEvent.Up))
{
animator.SetBool("swing", false);
m_Collider.enabled = !m_Collider.enabled;
}
if (TCKInput.GetAction("slideBtn", EActionEvent.Down))
{
if (timeStamp <= Time.time)
{
animator.SetBool("slide", true);
GameObject b = (GameObject)(Instantiate(bullet, transform.position + transform.right * 1.5f, Quaternion.identity));
b.GetComponent<Rigidbody2D>().AddForce(transform.right * 1000);
timeStamp = Time.time + 5;
}
}
if (TCKInput.GetAction("slideBtn", EActionEvent.Up))
{
animator.SetBool("slide", false);
}
if (TCKInput.GetAction("right", EActionEvent.Press))
{
move = -1;
}
if (TCKInput.GetAction("right", EActionEvent.Up))
{
animator.SetBool("run", false);
}
if (TCKInput.GetAction("left", EActionEvent.Press))
{
move = 1;
}
if (TCKInput.GetAction("left", EActionEvent.Up))
{
animator.SetBool("run", false);
}
if (objectCollider.IsTouching(anotherCollider))
{
canJump = true;
}
else
{
canJump = false;
}
}
private void Flip()
{
// Switch the way the player is labelled as facing.
m_FacingRight = !m_FacingRight;
// Multiply the player's x local scale by -1.
Vector3 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
}
void Hurt()
{
move = 4;
SceneManager.LoadScene(0);
}
protected void OnCollisionEnter2D(Collision2D collision)
{
EnemyHealth3 enemy = collision.collider.GetComponent<EnemyHealth3>();
if (enemy != null)
{
move = 0;
animator.SetBool("death", true);
m_Rigidbody2D.AddForce(new Vector2(0f, m_JumpForce));
StartCoroutine(ExecuteAfterTime(.1));
}
}
IEnumerator ExecuteAfterTime(double time)
{
yield return new WaitForSeconds((float)time);
Hurt();
}
}
#Code that is on the floor spawner script#
using UnityEngine;
using System.Collections;
public class Floor_Spawn_Script : MonoBehaviour
{
public GameObject[] obj;
private float oldPosition;
private float currentPosition;
private float ctr = 0;
private float inte = 10.19f;
// Use this for initialization
private void Start()
{
oldPosition = transform.position.x;
AddRoom(ctr * inte);
ctr += 1;
AddRoom(ctr * inte);
ctr += 1;
AddRoom(ctr * inte);
}
// Update is called once per frame
void Update()
{
currentPosition = transform.position.x;
if ((currentPosition - oldPosition) <= 9.595f)
{
AddRoom(ctr * inte);
oldPosition = transform.position.x;
ctr += 1;
}
}
void AddRoom(float roomCenter)
{
GameObject room = (GameObject)Instantiate(obj[Random.Range(0, obj.Length)]);
room.transform.position = new Vector3(roomCenter, 0f, 10f);
}
}```
CurrentlyGrounded Should flip to true and false. Instead, visual studio is reporting that it "Doesn't exist in the current context". How do I force this variable to exist EVERYWHERE in the script?
Making it public did absolutely nothing.
The problem occurs in the private void GroundCheck() method on Line 267.
using System;
using UnityEngine;
using UnityStandardAssets.CrossPlatformInput;
namespace UnityStandardAssets.Characters.FirstPerson
{
[RequireComponent(typeof (Rigidbody))]
[RequireComponent(typeof (CapsuleCollider))]
public class RigidbodyFirstPersonController : MonoBehaviour
{
[Serializable]
public class MovementSettings
{
public float ForwardSpeed = 8.0f; // Speed when walking forward
public float BackwardSpeed = 4.0f; // Speed when walking backwards
public float StrafeSpeed = 4.0f; // Speed when walking sideways
public float AirForwardSpeed = 8.0f; // Speed when flying forward
public float AirBackwardSpeed = 4.0f; // Speed when flying backwards
public float AirStrafeSpeed = 4.0f; // Speed when flying sideways
public bool CurrentlyGrounded = true;
public float RunMultiplier = 2.0f; // Speed when sprinting
public KeyCode RunKey = KeyCode.LeftShift;
public float JumpForce = 30f;
public AnimationCurve SlopeCurveModifier = new AnimationCurve(new Keyframe(-90.0f, 1.0f), new Keyframe(0.0f, 1.0f), new Keyframe(90.0f, 0.0f));
[HideInInspector] public float CurrentTargetSpeed = 8f;
#if !MOBILE_INPUT
private bool m_Running;
#endif
public void UpdateDesiredTargetSpeed(Vector2 input)
{
if (input == Vector2.zero) return;
if (input.x > 0 || input.x < 0 && CurrentlyGrounded == true)
{
//strafe
CurrentTargetSpeed = StrafeSpeed;
}
else if (input.x > 0 || input.x < 0 && CurrentlyGrounded == false)
{
//strafe
CurrentTargetSpeed = AirStrafeSpeed;
}
if (input.y < 0 && CurrentlyGrounded == true)
{
//backwards
CurrentTargetSpeed = BackwardSpeed;
}
else if (input.y < 0 && CurrentlyGrounded == false)
{
//backwards
CurrentTargetSpeed = AirBackwardSpeed;
}
if (input.y > 0 && CurrentlyGrounded == true)
{
//forwards
//handled last as if strafing and moving forward at the same time forwards speed should take precedence
CurrentTargetSpeed = ForwardSpeed;
}
else if (input.y > 0 && CurrentlyGrounded == false)
{
//forwards
//handled last as if strafing and moving forward at the same time forwards speed should take precedence
CurrentTargetSpeed = AirForwardSpeed;
}
#if !MOBILE_INPUT
if (Input.GetKey(RunKey))
{
CurrentTargetSpeed *= RunMultiplier;
m_Running = true;
}
else
{
m_Running = false;
}
#endif
}
#if !MOBILE_INPUT
public bool Running
{
get { return m_Running; }
}
#endif
}
[Serializable]
public class AdvancedSettings
{
public float groundCheckDistance = 0.01f; // distance for checking if the controller is grounded ( 0.01f seems to work best for this )
public float stickToGroundHelperDistance = 0.5f; // stops the character
public float slowDownRate = 20f; // rate at which the controller comes to a stop when there is no input
public bool airControl; // can the user control the direction that is being moved in the air
[Tooltip("set it to 0.1 or more if you get stuck in wall")]
public float shellOffset; //reduce the radius by that ratio to avoid getting stuck in wall (a value of 0.1f is nice)
}
public Camera cam;
public MovementSettings movementSettings = new MovementSettings();
public MouseLook mouseLook = new MouseLook();
public AdvancedSettings advancedSettings = new AdvancedSettings();
private Rigidbody m_RigidBody;
private CapsuleCollider m_Capsule;
private float m_YRotation;
private Vector3 m_GroundContactNormal;
private bool m_Jump, m_PreviouslyGrounded, m_Jumping, m_IsGrounded;
public Vector3 Velocity
{
get { return m_RigidBody.velocity; }
}
public bool Grounded
{
get { return m_IsGrounded; }
}
public bool Jumping
{
get { return m_Jumping; }
}
public bool Running
{
get
{
#if !MOBILE_INPUT
return movementSettings.Running;
#else
return false;
#endif
}
}
private void Start()
{
m_RigidBody = GetComponent<Rigidbody>();
m_Capsule = GetComponent<CapsuleCollider>();
mouseLook.Init (transform, cam.transform);
}
private void Update()
{
RotateView();
if (CrossPlatformInputManager.GetButtonDown("Jump") && !m_Jump)
{
m_Jump = true;
}
}
private void FixedUpdate()
{
GroundCheck();
Vector2 input = GetInput();
if ((Mathf.Abs(input.x) > float.Epsilon || Mathf.Abs(input.y) > float.Epsilon) && (advancedSettings.airControl || m_IsGrounded))
{
// always move along the camera forward as it is the direction that it being aimed at
Vector3 desiredMove = cam.transform.forward*input.y + cam.transform.right*input.x;
desiredMove = Vector3.ProjectOnPlane(desiredMove, m_GroundContactNormal).normalized;
desiredMove.x = desiredMove.x*movementSettings.CurrentTargetSpeed;
desiredMove.z = desiredMove.z*movementSettings.CurrentTargetSpeed;
desiredMove.y = desiredMove.y*movementSettings.CurrentTargetSpeed;
if (m_RigidBody.velocity.sqrMagnitude <
(movementSettings.CurrentTargetSpeed*movementSettings.CurrentTargetSpeed))
{
m_RigidBody.AddForce(desiredMove*SlopeMultiplier(), ForceMode.Impulse);
}
}
if (m_IsGrounded)
{
m_RigidBody.drag = 5f;
if (m_Jump)
{
m_RigidBody.drag = 0f;
m_RigidBody.velocity = new Vector3(m_RigidBody.velocity.x, 0f, m_RigidBody.velocity.z);
m_RigidBody.AddForce(new Vector3(0f, movementSettings.JumpForce, 0f), ForceMode.Impulse);
m_Jumping = true;
}
if (!m_Jumping && Mathf.Abs(input.x) < float.Epsilon && Mathf.Abs(input.y) < float.Epsilon && m_RigidBody.velocity.magnitude < 1f)
{
m_RigidBody.Sleep();
}
}
else
{
m_RigidBody.drag = 0f;
if (m_PreviouslyGrounded && !m_Jumping)
{
StickToGroundHelper();
}
}
m_Jump = false;
}
private float SlopeMultiplier()
{
float angle = Vector3.Angle(m_GroundContactNormal, Vector3.up);
return movementSettings.SlopeCurveModifier.Evaluate(angle);
}
private void StickToGroundHelper()
{
RaycastHit hitInfo;
if (Physics.SphereCast(transform.position, m_Capsule.radius * (1.0f - advancedSettings.shellOffset), Vector3.down, out hitInfo,
((m_Capsule.height/2f) - m_Capsule.radius) +
advancedSettings.stickToGroundHelperDistance, Physics.AllLayers, QueryTriggerInteraction.Ignore))
{
if (Mathf.Abs(Vector3.Angle(hitInfo.normal, Vector3.up)) < 85f)
{
m_RigidBody.velocity = Vector3.ProjectOnPlane(m_RigidBody.velocity, hitInfo.normal);
}
}
}
private Vector2 GetInput()
{
Vector2 input = new Vector2
{
x = CrossPlatformInputManager.GetAxis("Horizontal"),
y = CrossPlatformInputManager.GetAxis("Vertical")
};
movementSettings.UpdateDesiredTargetSpeed(input);
return input;
}
private void RotateView()
{
//avoids the mouse looking if the game is effectively paused
if (Mathf.Abs(Time.timeScale) < float.Epsilon) return;
// get the rotation before it's changed
float oldYRotation = transform.eulerAngles.y;
mouseLook.LookRotation (transform, cam.transform);
if (m_IsGrounded || advancedSettings.airControl)
{
// Rotate the rigidbody velocity to match the new direction that the character is looking
Quaternion velRotation = Quaternion.AngleAxis(transform.eulerAngles.y - oldYRotation, Vector3.up);
m_RigidBody.velocity = velRotation*m_RigidBody.velocity;
}
}
/// sphere cast down just beyond the bottom of the capsule to see if the capsule is colliding round the bottom
private void GroundCheck()
{
m_PreviouslyGrounded = m_IsGrounded;
RaycastHit hitInfo;
if (Physics.SphereCast(transform.position, m_Capsule.radius * (1.0f - advancedSettings.shellOffset), Vector3.down, out hitInfo,
((m_Capsule.height/2f) - m_Capsule.radius) + advancedSettings.groundCheckDistance, Physics.AllLayers, QueryTriggerInteraction.Ignore))
{
m_IsGrounded = true;
CurrentlyGrounded = true;
m_GroundContactNormal = hitInfo.normal;
}
else
{
m_IsGrounded = false;
CurrentlyGrounded = false;
m_GroundContactNormal = Vector3.up;
}
if (!m_PreviouslyGrounded && m_IsGrounded && m_Jumping)
{
m_Jumping = false;
}
}
}
}
What should be happening is that it's seen and changes as expected.
Instead, it's reported as nonexisting in the current context.
Don't listen to people who want to make everything static just to access stuff "more easily".
This actually might cause a lot of trouble as soon as you have more than exactly one instances of that class (e.g. if there are two players, or an AI uses the same component).
Another bad side effect is that you won't be able anymore to configure it via the Inspector e.g. for debugging or to give it the desired start value.
What you want to use instead is
moventSettings.CurrentlyGrounded
to access the value of your MovementSettings instance.
Just the same way you did it e.g. in
movementSettings.Running
You can assign it to a global variable.
public static class Globals
{
public static String value = "Sample Value"; // Modifiable
public static readonly String CODE_PREFIX = "TEST-"; // Unmodifiable
}
You can then retrieve the defined values anywhere in your code
String code = Globals.CODE_PREFIX + value.ToString();
Here is the code I currently have however I want to be able to move mid-jump.
as of now if I jump while moving I will carry on in that direction however I can't change the direction I am heading while in the air. This code was made using unity and the player that this code is attached to is a capsule.
private CharacterController charController;
[SerializeField] private AnimationCurve jumpFallOff;
[SerializeField] private float jumpMultipliyer;
[SerializeField] private KeyCode jumpKey;
private bool isJumping;
private void Awake()
{
charController = GetComponent<CharacterController>();
}
private void Update()
{
PlayerMovement();
}
private void PlayerMovement()
{
float horziInput = Input.GetAxis(horizontalInputName) * movementSpeed;
float vertInput = Input.GetAxis(verticalInputName) * movementSpeed;
Vector3 forwardMovement = transform.forward * vertInput;
Vector3 rightMovement = transform.right * horziInput;
charController.SimpleMove(forwardMovement + rightMovement);
JumpInput();
}
private void JumpInput()
{
if(Input.GetKeyDown(jumpKey) && !isJumping)
{
isJumping = true;
StartCoroutine(JumpEvent());
}
}
private IEnumerator JumpEvent()
{
charController.slopeLimit = 90.0f;
float timeInAir = 0.0f;
do
{
float jumpForce = jumpFallOff.Evaluate(timeInAir);
charController.Move(Vector3.up * jumpForce * jumpMultipliyer * Time.deltaTime);
timeInAir += Time.deltaTime;
yield return null;
} while (!charController.isGrounded && charController.collisionFlags != CollisionFlags.Above);
charController.slopeLimit = 45.0f;
isJumping = false;
}
i've been having this problem with my 2d sprites (enemies characters in my case) where if I have a prefab already made from one scene that works just fine, and use that prefab in another scene, the size is not the same, but it behaves the same if it runs into a wall or something (it turns the other direction). It's not the script because the movement script is attached to other gameobjects that as of now behave the same way and those prefabs get imported to other scenes just fine. Does anyone know if this is a Unity bug or something? It's not a script issue I'm sure. In fact I know it isn't because it's happened with other enemies with different scripts. Sometimes this issue only happens in one scene, sometimes several, sometimes all of them, as long as it's not the original scene the game object and prefab was created in.
I should also mention that when I build the actual game, the game objects work as they should. It's only when I'm in the unity program itself that this is happening. But I can't properly test some scenes unless I were to build the game scene over and over which would be very counterproductive.
here's the script attached to the enemy for those insistent.
using UnityEngine;
using System.Collections;
public class foeHP : MonoBehaviour {
public GameObject deathFlamePrefab;
Rigidbody2D erb;
public float Walk= 2.5f;
private float idle = 0f;
public float move = 2.5f;
public float hp = 3f;
private slicer slicy;
Animator anim;
private bool alive = true;
private bool damager = false;
private float invuln = 0f;
private bool nothurt = true;
public float wallCheckRadius;
public LayerMask whatIsWall;
private bool wallHit;
private bool goRight;
private bool atEdge = false;
public bool spotted;
public float xScale;
public float yScale;
public Transform wallCheck;
public Transform edgeCheck;
public GameObject bonePrefab;
public Transform boneSpawn;
public float fireDelay = 0.5f;
public float coolDownTimer = 0f;
public float timer3 = 0.75f;
private bool damagePlayed = false;
void Start ()
{
anim = GetComponent<Animator>();
erb = GetComponent<Rigidbody2D> ();
}
void Update ()
{
invuln -= Time.deltaTime;
Recover ();
HandleMovement ();
notHurting ();
// Born ();
damagePlayed = false;
}
public void takeDamage (float amount)
{
hp -= amount;
damager = true;
if (!damagePlayed && alive && hp <= 0)
{
Instantiate (deathFlamePrefab, transform.position, transform.rotation);
Destroy (gameObject);
}
if (alive && hp > 0) {
anim.SetTrigger ("damaged");
invuln = 0.5f;
gameObject.layer = 14;
Invoke ("layerReturn", timer3);
}
if (alive && hp > 0 && !damagePlayed) {
soundManager.PlaySFX ("enemyHit");
damagePlayed = true;
}
}
void layerReturn()
{
gameObject.layer = 12;
}
public void HandleMovement()
{
if (wallCheck == null) {
return;
} else {
wallHit = Physics2D.OverlapCircle (wallCheck.position, wallCheckRadius, whatIsWall);
atEdge = Physics2D.OverlapCircle (edgeCheck.position, wallCheckRadius, whatIsWall);
if (wallHit || !atEdge)
goRight = !goRight;
if (goRight) {
transform.localScale = new Vector3 (-xScale, yScale, 1f);
erb.velocity = new Vector2 (move, erb.velocity.y);
anim.SetFloat ("walk", Mathf.Abs (move));
} else {
transform.localScale = new Vector3 (xScale, yScale, 1f);
erb.velocity = new Vector2 (-move, erb.velocity.y);
anim.SetFloat ("walk", Mathf.Abs (move));
}
}
Physics2D.IgnoreLayerCollision (12, 12);
}
public void Recover ()
{
if (invuln <= 0)
gameObject.layer = 12;
nothurt = false;
if (invuln <= 0)
anim.SetLayerWeight (1, 0);
nothurt = true;
}
public void notHurting()
{
if (invuln > 0)
erb.velocity = Vector2.zero;
}
void OnTriggerEnter2D (Collider2D other)
{
if (other.gameObject.tag == "Player")
spotted = true;
else
spotted = false;
}
/* void Born ()
{
coolDownTimer -= Time.deltaTime;
if (spotted && coolDownTimer <= 0)
{
coolDownTimer = fireDelay;
anim.SetTrigger ("Throw");
Instantiate (bonePrefab, boneSpawn.position, boneSpawn.rotation);
if (!spotted)
fireDelay = 0;
}
}
*/
}