- Home /
Rotate An Object Toward The Direction The Joystick Is Pressed, can you help me? I am stuck
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(Rigidbody2D))]
public class movescript : MonoBehaviour {
public FixedJoystick joystick;
public float velocity=10f;
private float h;
private float v;
private float baseSpeed = 10.0f;
private float rotateXspeed = 10.0f;
private float rotateYspeed = 1.5f;
private Rigidbody2D rb;
private void Start()
{
rb = GetComponent<Rigidbody2D>();
}
private void FixedUpdate()
{
h = joystick.Horizontal;
v = joystick.Vertical;
float angle = Mathf.Atan2(h, v);
float zRot= angle * Mathf.Rad2Deg;
rb.velocity = (new Vector3(h*baseSpeed, v*baseSpeed, zRot));
}
Comment
@Bunny83 @Eric5h5 @aldonaletto @duck @whydoidoit @crazy$$anonymous$$night
Answer by GanemVisk · Dec 15, 2019 at 04:38 PM
I'm not familiar with 2d, but here is what I see. Velocity is a Vector2, if it is assigned a Vector3, it discards the z-axis. Even if it didn't, the z-axis in velocity is also a direction, not a rotation. If the velocity had a positive z, the object would go away from the screen, as in a tunnel. To rotate one option is to use rb.rotate(zRot)
and it will immediately face that direction, which I suppose is the desired effect.