- Home /
2D character control script in a 3D world
I am building a hack and slash-side scroller that is loosely based off of Castle Crashers. The game uses 2D assets in a 3D world with limitations so that there is full 3D movement in a restricted area. I have all the sprites loaded into unity with proper 3D physics. The player has a 3D based character controller script attached but will only face one direction when moving. I cant seem to find scripting the change the transform ration value to 180 degrees and back. I only need the character to flip along the Y-axis. could anyone lend a hand or give some advice? Here is my current script (its was originally made for a basic 3d fps) using System.Collections; using System.Collections.Generic; using UnityEngine;
public class basicController : MonoBehaviour {
// Update is called once per frame
void Update () {
Debug.Log ("horizontal = " + Input.GetAxis ("Horizontal"));
}
}
using UnityEngine; using System.Collections;
public class Controller : MonoBehaviour {
// public variables
public float moveSpeed = 3.0f;
public float gravity = 9.81f;
private CharacterController myController;
// Use this for initialization
void Start () {
// store a reference to the CharacterController component on this gameObject
// it is much more efficient to use GetComponent() once in Start and store
// the result rather than continually use etComponent() in the Update function
myController = gameObject.GetComponent<CharacterController>();
}
// Update is called once per frame
void Update () {
// Determine how much should move in the z-direction
Vector3 movementZ = Input.GetAxis("Vertical") * Vector3.forward * moveSpeed * Time.deltaTime;
// Determine how much should move in the x-direction
Vector3 movementX = Input.GetAxis("Horizontal") * Vector3.right * moveSpeed * Time.deltaTime;
// Convert combined Vector3 from local space to world space based on the position of the current gameobject (player)
Vector3 movement = transform.TransformDirection(movementZ+movementX);
// Apply gravity (so the object will fall if not grounded)
movement.y -= gravity * Time.deltaTime;
//Debug.Log ("Movement Vector = " + movement);
// Actually move the character controller in the movement direction
myController.Move(movement);
//test script to flip character 180 degrees on y axis
if (Input.GetKey (KeyCode.LeftArrow))
transform.right *= -1;
//transform.eulerAngles = new Vector3(0,180,0);
else if (Input.GetKey (KeyCode.RightArrow))
transform.right *= -1;
//transform.eulerAngles = new Vector3(0,0,0);
}
}
Your answer
Follow this Question
Related Questions
Character falls over and bugs out when animator is enabled 0 Answers
How do I make my character controller jump when I use this code? 0 Answers
Convert Rigidbody code to CharacterController usable 0 Answers
Multiple Cars not working 1 Answer
I'm new to Unity and C# and I need help with a character control problem. 0 Answers