Quantcast
Viewing latest article 2
Browse Latest Browse All 90

Separating Player Input from Player Behavior

I was attempting to organize these scripts a little better by separating the input and behavior of the character into two scripts. It works alright until I actually try to set up the raycast and booleans so that the player won't continously jump. public void Jump (float jumpHeight) { playerController.isGrounded = false; rigidbody.AddForce (new Vector3 (0, jumpHeight, 0), ForceMode.Force); } public void FixedUpdate () { playerController.isGrounded = Physics.Raycast (transform.position, -Vector3.up, .5f); } } So if I just leave in the jump function (inside PlayerPhysics), then it works, but once I add the raycast and booleans, I won't actually get any errors, but the player will stop jumping. This works if I put the Jump Function and Fixed Update function in the PlayerController, (where the actual input is) but not if I put them in the other script. Why is this? using UnityEngine; using System.Collections; [RequireComponent(typeof(PlayerPhysics))] public class PlayerController : MonoBehaviour { //Player Handling public float speed = 8; public float acceleration = 30; public float gravity = 20; public bool isGrounded = false; public float jumpHeight = 500; public float currentSpeed; public float targetSpeed; private Vector2 amountToMove; private PlayerPhysics playerPhysics; // Use this for initialization void Start () { playerPhysics = GetComponent(); } // Update is called once per frame void Update () { if(Input.GetButtonDown("Jump") && isGrounded) { //Jump(); playerPhysics.Jump (jumpHeight); } targetSpeed = Input.GetAxisRaw("Horizontal") * speed; currentSpeed = IncrementTowards ( currentSpeed, targetSpeed, acceleration); amountToMove.x = currentSpeed; playerPhysics.Move(amountToMove * Time.deltaTime); } //Increase n towards target by speed private float IncrementTowards(float n, float target, float a) { if (n == target) { return n; } else { float dir = Mathf.Sign(target - n); n += a * Time.deltaTime * dir; return (dir == Mathf.Sign(target - n))? n: target; } } && using UnityEngine; using System.Collections; public class PlayerPhysics : MonoBehaviour { public PlayerController playerController; void Start () { playerController = GetComponent(); } public void Move(Vector2 moveAmount) { float deltaY = moveAmount.y; Vector2 finalTransform = new Vector2(deltaX,deltaY); transform.Translate (finalTransform); } public void Jump (float jumpHeight) { playerController.isGrounded = false; rigidbody.AddForce (new Vector3 (0, jumpHeight, 0), ForceMode.Force); } public void FixedUpdate () { playerController.isGrounded = Physics.Raycast (transform.position, -Vector3.up, .5f); } }

Viewing latest article 2
Browse Latest Browse All 90

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>