Mario Galaxy -ish controls problem

Hi there!

I am prototyping a Mario Galaxy style (“faux”) gravity system. While the attraction force didn’t give me much trouble, the controls are giving me a headache.

You can move. You can jump. But when you do both things simultaneously, everything goes whack.

This is my bare-bones code:

using UnityEngine;
using System.Collections;

public class PlayerController : MonoBehaviour {

	private float moveSpeed = 15;
	private Vector3 moveDirection;

	void Start() {

	}

	void Update() {
		moveDirection = new Vector3(Input.GetAxisRaw("Horizontal"),0,Input.GetAxisRaw("Vertical")).normalized;
	}

	void FixedUpdate() {
		rigidbody.MovePosition (rigidbody.position + transform.TransformDirection (moveDirection) * moveSpeed * Time.deltaTime);
	}
	
	void OnCollisionStay (Collision col)
	{
		if (Input.GetKeyDown (KeyCode.Space))
			rigidbody.velocity += transform.up * 20;
	}
}

Any leads?

Thanks a lot in advance!

You don’t explain what is actually happening when things "

 whack", but you probably shouldn't be modifying the velocity of the rigidbody outside of the FixedUpdate loop.  You should also be getting your control input in Update.

    
    void Update()
    {
        moveDirection = new Vector3(Input.GetAxisRaw("Horizontal"),0,Input.GetAxisRaw("Vertical")).normalized;
        isJumping = Input.GetKeyDown (KeyCode.Space);
    }

    void FixedUpdate() 
    {
        rigidbody.MovePosition (rigidbody.position + transform.TransformDirection (moveDirection) * moveSpeed * Time.deltaTime);
        if (isJumping)
            rigidbody.velocity += transform.up * 20;
    }
     
    void OnCollisionEnter (Collision col)
    {
        // if (col is ground)  -- only set isJumping to false if we touch the ground
            isJumping = false;
    }
    
    bool isJumping;


You might also consider using [rigidbody.AddForce][1] instead of modifying the velocity directly.


  [1]: http://docs.unity3d.com/ScriptReference/Rigidbody.AddForce.html