- Home /
Question by
RainaTaleth · Aug 30, 2014 at 03:29 PM ·
c#movementcharactercontrollerjump
Jump and move (CharacterController.velocity) C#
I am writing a simple code for mobile platformer the idea is that I have two touch buttons for movement forward and back and one button for jump. It works fine but the problem is that if I press movement button and then I jump the character controller jugges back before jumping. I was trying to figure out why it does that but I have run out of options.
Here is the code:
using UnityEngine;
using System.Collections;
public class CharacterMovement : MonoBehaviour {
public TouchControll moveFWD;
public TouchControll moveBWD;
public TouchControll jumpUP;
private float speed = 5.0f;
private float jumpSpeed = 18.0f;
private bool canJump = true;
private Vector3 velocity;
private Vector3 movement;
private CharacterController character;
private Transform thisTransform;
private bool jump = false;
// Use this for initialization
void Start () {
thisTransform = transform;
character = gameObject.GetComponent<CharacterController>();
GameObject spawn = GameObject.Find( "Spawn" );
if ( spawn ) thisTransform.position = spawn.transform.position;
}
// Update is called once per frame
void Update () {
movement = Vector3.zero;
if ( moveFWD.fingerDown ) movement = Vector3.right * speed;
else if ( moveBWD.fingerDown ) movement = Vector3.right * -speed;
if(character.isGrounded){
jump = false;
if(!jumpUP.fingerDown) canJump = true;
if(canJump && jumpUP.fingerDown) {
jump = true;
canJump = false;
}
if ( jump ) {
velocity = character.velocity;
velocity.y = jumpSpeed;
}
} else {
velocity.y += Physics.gravity.y * Time.deltaTime;
//movement.x *= 0.5f;
}
movement += velocity;
movement += Physics.gravity;
movement *= Time.deltaTime;
character.Move( movement );
if ( character.isGrounded ) velocity = Vector3.zero;
}
}
screenshot 2014-08-30 16.33.25.png
(103.2 kB)
Comment
Your answer
Follow this Question
Related Questions
Jump with Character Controller 1 Answer
Making a bubble level (not a game but work tool) 1 Answer
My Player can't jump - coding 1 Answer
[C#] Jump on slopes 1 Answer
[C#]CharacterController Turning 2 Answers