Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Velocity Towards Angle
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
public Rigidbody2D rb;
public float rotateSpeed = 300f;
public float angularSpeed = 10f;
private float yAxis;
private float xAxis;
// Use this for initialization
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
yAxis = Input.GetAxisRaw("Vertical");
xAxis = Input.GetAxisRaw("Horizontal");
}
void FixedUpdate()
{
rb.velocity = new Vector2(0, 0);
rb.angularVelocity = 0;
if (xAxis > 0)
{
transform.Rotate(new Vector3(0, 0, Time.deltaTime * -rotateSpeed));
}
else if (xAxis < 0)
{
transform.Rotate(new Vector3(0, 0, Time.deltaTime * rotateSpeed));
}
float angle = transform.eulerAngles.z;
if (yAxis > 0)
{
rb.velocity = new Vector2(Mathf.Cos(Mathf.Deg2Rad * angle), Mathf.Sin(Mathf.Deg2Rad * angle)) * angularSpeed;
}
else if (yAxis < 0)
{
rb.velocity = new Vector2(Mathf.Cos(Mathf.Deg2Rad * angle), Mathf.Sin(Mathf.Deg2Rad * angle)) * -angularSpeed;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.