- Home /
Character facing joystick direction
Good day everyone. I'm trying to insert 3D animation to rotate my character following my joystick facing. Left - character face left, right - character face right. This is a 3D side-view platformer game. Any advice on how to implement it? Many thanks.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MyScript : MonoBehaviour
{
protected Joystick joystick;
protected Joybutton joybutton;
protected bool jump;
private Animator anim;
void Start()
{
joystick = FindObjectOfType<Joystick>();
joybutton = FindObjectOfType<Joybutton>();
anim = GetComponent<Animator>();
}
void Update()
{
var rigidbody = GetComponent<Rigidbody>();
rigidbody.velocity = new Vector2(joystick.Horizontal * 10f, joystick.Vertical * 10f); //My joystick
if (!jump && joybutton.Pressed)
{
jump = true;
anim.Play("Attack", 0, 0.25f); //Play attack animation
//rigidbody.velocity += Vector3.down * 100f;
}
if(jump && !joybutton.Pressed)
{
jump = false;
}
}
}
Perhaps you can take a look at this following thread: https://forum.unity.com/threads/a-free-simple-smooth-mouselook.73117/
Answer by TreyH · Nov 21, 2019 at 09:19 PM
Like a LookRotation?
this.transform.rotation = Quaternion.LookRotation(joystick.Horizontal * Vector3.right, Vector3.up);
You can clean things up a bit by checking which direction you're facing (untested):
private float lastHorizontal = 0;
void Update()
{
var horizontal = joystick.Horizontal;
if (horizontal * lastHorizontal < 0 && Mathf.Abs(horizontal) > Mathf.Epsilon)
{
var lookDirection = Mathf.Sign(horizontal) * Vector3.right;
this.transform.rotation = Quaternion.LookRotation(lookDirection, Vector3.up);
}
lastHorizontal = horizontal;
}
where the horizontal * lastHorizontal < 0
will check if your sign changed, meaning there's a new direction.
Thank you kind stranger! I can't believe I overlook this and it's pretty much working well. Have a great day.
Excuse me kind stranger. Can you help me with another question? Thanks!
https://answers.unity.com/questions/1680925/movement-similar-to-hungry-shark-evolution.html
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Weird angle returned 1 Answer
Enemy only moves in a line 1 Answer