x


2D Player Movement C#

I have a script for basic movement that works, but I want to be able to steer the players horizontal movement while midair. I also would like to be able to determine the force or the height of the jump by how long I hold the jump button.

Here's my working movement script so far:

 using UnityEngine;
 using System.Collections;
 
 public class Player_movement : MonoBehaviour
 {
     public float f_speed;
     public float f_jumpSpeed;
     public float f_gravity;
     private Vector3 v3_moveDirection = Vector3.zero;
     private CharacterController controller;
     
     void Awake ()
     {
         controller = GetComponent<CharacterController>();
     }
     
     void Update ()
     {
         if (controller.isGrounded)
         {    
             v3_moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0, 0);
             v3_moveDirection *= f_speed;
             
             if (Input.GetButton("Jump"))
             {
                 v3_moveDirection.y = f_jumpSpeed;
             }
         }
 
         v3_moveDirection.y -= f_gravity * Time.deltaTime;
         controller.Move(v3_moveDirection * Time.deltaTime);
     }
     
 }
more ▼

asked Feb 19, 2012 at 01:14 AM

maniac222 gravatar image

maniac222
16 4 4 7

(comments are locked)
10|3000 characters needed characters left

2 answers: sort voted first

i get this error.
NullReferenceException: Object reference not set to an instance of an object PlayerMovement.Update () (at Assets/PlayerMovement.cs:19) -------- How can i fix it

more ▼

answered Oct 21, 2012 at 03:09 PM

AndreasDp gravatar image

AndreasDp
1 2 2

Did you add a Character Controller?

May 22, 2013 at 11:21 AM Cream92
(comments are locked)
10|3000 characters needed characters left

Change your line 14 to: controller = this.GetComponent(); Put this script inside who will make the action of movement.

more ▼

answered Jul 19, 2013 at 03:28 AM

fdfragoso gravatar image

fdfragoso
1

(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x10943
x3294
x2658
x1407

asked: Feb 19, 2012 at 01:14 AM

Seen: 11389 times

Last Updated: Jul 19, 2013 at 03:28 AM