Question by
tobio24 · Aug 13, 2020 at 09:43 AM ·
scripting problemmovement
2D Movement Relative to Rotation
I currently have a character with the camera as the child object and using the following script to move/rotate. I'm not sure how to make the character move forward relative to the rotation instead of the world. Any help?
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class BasicMovement : MonoBehaviour { public float speed; public Animator animator; public float rotSense = 50.0f;
private Rigidbody2D rb;
private Vector2 moveVelocity;
private float rotZ;
private Quaternion localRotation;
void Start(){
rb = GetComponent<Rigidbody2D>();
}
void Update(){
if(Input.GetKey(KeyCode.Q)) {
rotZ += Time.deltaTime * rotSense;
}
if(Input.GetKey(KeyCode.E)) {
rotZ -= Time.deltaTime * rotSense;
}
if(Input.GetKey(KeyCode.Z)) {
rotZ = 0;
}
Vector2 moveInput = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
moveVelocity = moveInput.normalized * speed;
animator.SetFloat("Horizontal", moveInput.x);
animator.SetFloat("Vertical", moveInput.y);
animator.SetFloat("Magnitude", moveInput.magnitude);
if (moveInput.magnitude > 0){
animator.SetFloat("lastHorizontal", moveInput.x);
animator.SetFloat("lastVertical", moveInput.y);
}
}
void FixedUpdate(){
rb.MovePosition(rb.position + moveVelocity * Time.fixedDeltaTime);
rb.rotation = rotZ;
}
}
Comment