Hello everyone. I’d heavily appreciate it if I could get some help with my movement script, as stated below. Sorry if I repeat myself a little bit, I’m just trying to get the point across.
The goal of this movement script is to create a rigidbody that slides across the ground to move, but is still effected by physics. (In this case, a square.) It should slide against the ground moving left/right without rotating, but still be prone to rotating when jumping/falling, or otherwise being flipped over. That said, it’s directional movement should keep orientation even if the object itself is flipped over. (Say it is flipped over on another side, it will still move right when the move-right button is pressed.)
Instead of this, the current script causes the rigidbody (in this case again, a square) to rotate itself in whichever direction it may be. Mind you, the only directions it is meant to go is up/down, and left/right in it’s 2D space.
Note: The code below is not made by me. It is a modified script from the Unity Wiki that was built for 3D movement, that I modified to fit my needs. You can find the original here. (Also note the below code is in C#)
using UnityEngine;
using System.Collections;
public class BasicMovement : MonoBehaviour {
// These variables are for adjusting in the inspector how the object behaves.
public float maxSpeed = 7;
public float force = 8;
public float jumpSpeed = 5;
// These variables are there for use by the script and don't need to be edited.
private int state = 0;
private bool grounded = false;
private float jumpLimit = 0;
// This part detects whether or not the object is grounded and stores it in a variable.
void OnCollisionEnter ()
{
state ++;
if(state > 0)
{
grounded = true;
}
}
void OnCollisionExit ()
{
state --;
if(state < 1)
{
grounded = false;
state = 0;
}
}
public virtual bool jump
{
get
{
return Input.GetButtonDown ("Jump");
Debug.Log ("Hello");
}
}
public virtual float horizontal
{
get
{
return Input.GetAxis("Horizontal") * force;
}
}
public virtual float vertical
{
get
{
return Input.GetAxis("Vertical") * force;
}
}
// This is called every physics frame.
void FixedUpdate ()
{
// If the object is grounded and isn't moving at the max speed or higher apply force to move it.
if(rigidbody.velocity.magnitude < maxSpeed && grounded == true)
{
rigidbody.AddForce (Vector3.forward * vertical);
rigidbody.AddForce (Vector3.right * horizontal);
}
// This part is for jumping. I only let jump force be applied every 10 physics frames so
// the player can't somehow get a huge velocity due to multiple jumps in a very short time.
if(jumpLimit < 10) jumpLimit ++;
if(jump && grounded && jumpLimit >= 10)
{
rigidbody.velocity = rigidbody.velocity + (Vector3.up * jumpSpeed);
jumpLimit = 0;
}
}
}