Tilting Sprite / Gameobject

Dear all,

I am currently going through the unity 2D course (Laser Defender) and struggle to implement something I want to add. Basically, the player ship should be tilted a bit when it is moved left or right:

I thought this would be a easy thing…but somehow I really struggle. I already searched through code sniplets but was not able to implement what I need. The player ship does weird things I do not understand :wink:

This is what I have currently to get the ship tilted but it does not work as intended:

    float z = Input.GetAxis("Horizontal") * tilting;
    Vector3 euler = transform.localEulerAngles;
    euler.z = Mathf.Lerp(euler.z, z, 2.0f * Time.deltaTime);
    transform.localEulerAngles = euler;

tilting is an Integer with the tilting angle assigned to it.

Thanks for your help!

With best regards,
Weltenlicht

Hi Weltenlicht,

First of all, good job on challenging yourself. Also, your code looks fine so far. At least, the relevant methods are there. What do you mean by “it does not work as intended”? What is the outcome during runtime?

I am guessing your thing is spinning around. First, Cache your Vector3 Euler once then leave it cause it is updating each time causing it to spin rather than tilt. So do Vector3 euler = transform.localEulerAngles in the start method and make sure your sprite is pointing in a base direction.

Hi Nina and AstroneerKing,

thank you very much for the comments and help.
The sprite was indeed spinning around. Caching the euler vector solved the problem to 100%. One last thing I had to do was to multiply the horizontal input with the negative tilting to achieve tilting in the correct direction.

Final Code is:
In the Start() method:
eulerVector = transform.localEulerAngles;

Update() method:

float z = Input.GetAxis("Horizontal") * -tilting;
eulerVector.z = Mathf.Lerp(eulerVector.z, z, tiltingSpeed * Time.deltaTime);
transform.localEulerAngles = eulerVector;

With best regards,
Weltenlicht

1 Like

Does that mean you fixed the issue? :slight_smile:


See also:

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms