- Home /
Rewriting movement on tranform to Rigidbody2D
Hi! I have this player controls made with transform, but unfortunately I'm very new to code and can't work further without Rigidbody2D. So I need to rewrite this transform controls to Rigidbody2d! Code at pastebin : https://pastebin.com/CKQ1JySx using System; using UnityEngine; using UnityEngine.UI; using UnityEngine.EventSystems; using UnityStandardAssets.CrossPlatformInput; public class PlayerMovement : MonoBehaviour { public float verticalInputAcceleration = 1; public float horizontalInputAcceleration = 1; public float maxSpeed = 1; public float rotationSpeed = 1; public float acceleration = 1; public float velocityDrag = 1; //public Vector3 velocity; private float zRotationVelocity; private Vector3 velocity; private void Update() { // apply velocity drag velocity = velocity * (1 - Time.deltaTime * velocityDrag); // clamp to maxSpeed velocity = Vector3.ClampMagnitude(velocity, maxSpeed); // update transform transform.position += velocity * Time.deltaTime; } private void FixedUpdate() { Vector3 direction = new Vector3(CrossPlatformInputManager.GetAxis("Horizontal") * horizontalInputAcceleration, CrossPlatformInputManager.GetAxis("Vertical") * verticalInputAcceleration, 0 ); bool move = !(Mathf.Approximately (direction.x, 0) && Mathf.Approximately (direction.y, 0)); if (move) { float angle = Mathf.Atan2 (direction.y, direction.x) * Mathf.Rad2Deg; Quaternion rotation = Quaternion.AngleAxis (angle - 90, Vector3.forward); transform.rotation = Quaternion.Slerp (transform.rotation, rotation, Time.deltaTime * rotationSpeed); velocity += transform.up * Mathf.Max(Mathf.Abs(direction.x), Mathf.Abs(direction.y)) * Time.deltaTime * 0.1f * acceleration; } } }
Answer by BOB_KSE · Dec 26, 2017 at 07:08 PM
Is this the standard assets 2d Character-Controller code? Anyway its hard to understand if you are new to Unity/Coding. You can use this 2D platformer code I made a while back. it uses Rigidbody2D and uses frame by frame movement instead of using axis. It will work on unity 2017. Hope this helps you...