- Home /
The question is answered, right answer was accepted
How to flip an object ?
UNITY 2D C#
I try to turn the face of the object to the right when it moves to the right and to the left, when it moves to the left.
How to do it?
I tried something like that, but my object, apart from rotating left and right, when it has to look right, also turns upside down.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AccelerometrInput : MonoBehaviour {
public bool lookleft = true;
public float speed = 10.0F;
void Update() {
Vector3 dir = Vector3.zero;
dir.x = Input.acceleration.x;
dir.z = 0;
if (dir.sqrMagnitude > 1)
dir.Normalize ();
dir *= Time.deltaTime;
transform.Translate (dir * speed);
if (dir.x < 0 && !lookleft || dir.x > 0 && lookleft) {
Flip ();
}
}
void Flip (){
lookleft = !lookleft;
Vector3 charscale = transform.localScale;
charscale *= -1;
transform.localScale = charscale;
}
}
Answer by polan31 · Feb 05, 2019 at 07:57 PM
Solved :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MoveScript : MonoBehaviour
{
bool facingLeft = true;
private Rigidbody2D rigid;
private Vector2 movement;
public float movementSpeed = 10f;
void Start()
{
rigid = GetComponent<Rigidbody2D>();
}
void Update()
{
movement = new Vector2(Input.acceleration.x , 0) * movementSpeed;
rigid.AddForce(movement);
}
void LateUpdate (){
Vector3 localScale = transform.localScale;
if (Input.acceleration.x < -0.1)
{
facingLeft = true;
}
else if (Input.acceleration.x > 0.1 )
{
facingLeft = false;
}
if (((facingLeft ) && (localScale.x < 0 )) || ((!facingLeft) && (localScale.x > 0 ))) {
localScale.x *= -1;
}
transform.localScale = localScale;
}
}
Answer by mjdb3d · Oct 20, 2018 at 06:59 AM
Change this
charscale *= -1;
With this
charscale.x *= -1;
error CS0019: Operator *=' cannot be applied to operands of type
UnityEngine.Vector3' and `UnityEngine.Vector3
Okay, now it works.
However, I have a problem.
When I reduce the object on a scale, for example it is too big, then this script does not work anymore because it smears the object.
Any suggestions?
I tried to reduce the value of Vector 3 in the script, but it does not work....
I tested them both and they works fine:
Scale object direct pass Vector3 for scale
Can you specific what the issue?