Created
February 5, 2018 23:12
-
-
Save h1ggs/c6635c210e41be84619fabb7cc62ce61 to your computer and use it in GitHub Desktop.
movement v2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Collections; | |
using System.Collections.Generic; | |
using UnityEngine; | |
public class Movement : MonoBehaviour { | |
public Vector2 speed = new Vector2(50, 0); | |
public float jumpHeight; | |
public LayerMask mask; | |
private int layer_mask; | |
private float xSpeed; | |
public bool grounded; | |
// 2 - Store the movement and the component | |
public bool jump = false; | |
private Vector2 movement; | |
private Rigidbody2D rigidbodyComponent; | |
void Start(){ | |
} | |
void Update() | |
{ | |
// 3 - Retrieve axis information | |
float inputX = Input.GetAxis("Horizontal"); | |
float inputY = Input.GetAxis("Vertical"); | |
xSpeed = inputX; | |
// 4 - Movement per direction | |
movement = new Vector2( | |
speed.x * inputX, | |
speed.y * inputY); | |
if (Input.GetKeyDown (KeyCode.Space)) { | |
grounded = (Physics2D.Raycast((new Vector3(transform.position.x, transform.position.y, 0)), Vector3.down, 0.8f, mask)); // raycast down to look for ground is not detecting ground? only works if allowing jump when grounded = false; // return "Ground" layer as layer | |
Debug.DrawRay((new Vector3(transform.position.x, transform.position.y, 0)), Vector3.down, Color.green, 5); | |
jump = true; | |
} | |
} | |
void FixedUpdate() | |
{ | |
// 5 - Get the component and store the reference | |
if (rigidbodyComponent == null) rigidbodyComponent = GetComponent<Rigidbody2D>(); | |
// 6 - Move the game object | |
Vector2 temp = new Vector2 (speed.x * xSpeed, rigidbodyComponent.velocity.y); | |
rigidbodyComponent.velocity = temp; | |
if (jump && grounded) { | |
Vector2 jumpNow = new Vector2 (0, jumpHeight); | |
rigidbodyComponent.AddForce (jumpNow, ForceMode2D.Impulse); | |
jump = false; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment