Hi everybody! I’m writing a very very basic program: a mouse that runs across the screen, bouncing on edges. I wrote this so far:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PredaControllerScript : MonoBehaviour
{
public float movX, movY, alfa;
public int maxV, minV;
// Use this for initialization
void Start()
{
minV = 5;
maxV = 15;
transform.position = new Vector3(0, 0, 0);
changeDirection("Edge0");
}
void FixedUpdate()
{
GetComponent<Rigidbody2D>().velocity = new Vector2(movX, movY);
}
void changeDirection(string edge)
{
int rand;
movX = Random.Range(minV, maxV);
movY = Random.Range(minV, maxV);
if (edge == "Edge0")
{
do
{
rand = Random.Range(-10, +10);
if (rand > 0)
movX = -movX;
} while (rand == 0);
do
{
rand = Random.Range(-10, +10);
if (rand > 0)
movY = -movY;
} while (rand == 0);
}
else if (edge == "Edge1")
{
do
{
rand = Random.Range(-10, +10);
if (rand > 0)
movX = -movX;
} while (rand == 0);
movY = -movY;
}
else if (edge == "Edge2")
{
movX = movX; //lol
do
{
rand = Random.Range(-10, +10);
if (rand > 0)
movY = -movY;
} while (rand == 0);
}
else if (edge == "Edge3")
{
do
{
rand = Random.Range(-10, +10);
if (rand > 0)
movX = -movX;
} while (rand == 0);
movY = movY; //lol
}
else if (edge == "Edge4")
{
movX = -movX;
do
{
rand = Random.Range(-10, +10);
if (rand > 0)
movY = -movY;
} while (rand == 0);
}
alfa = Mathf.Acos(movX / Mathf.Sqrt((movX * movX) + (movY * movY)));
//transform.Rotate(0, 0, -GetComponent<Rigidbody2D>().rotation + alfa);
GetComponent<Rigidbody2D>().rotation = alfa;
}
void OnCollisionEnter2D(Collision2D collision)
{
changeDirection(collision.gameObject.name);
}
}
My mouse sprite has a Rigidbody2D and a CircleCollider2D.
When I launch the program the sprite runs across, but if I enabled the “freeze rotation” option in the rigidbody2D it will always have a direction of 0 degrees, and if I didn’t enable that option it will rotate randomly (following physical rules) in the screen. How can I do to make the mouse look in the direction he’s running?
Thank you in advance! bye!
PS: sorry for my English