So I’m trying to create a script where the enemy locates the player and automatically move towards them, but I have run into a bit of an error as when I click play, the enemy is orientated wrong.
My code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyMovement : MonoBehaviour {
public Transform player;
private Rigidbody2D rb;
private Vector2 movement;
public float moveSpeed;
void Start() {
rb = this.GetComponent<Rigidbody2D>(); //Gets ridibody2d component of enemy and assigns it to rb
}
void Update() {
Vector3 direction = player.position - transform.position; //Finds direction of enemy relative to player
float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg; //Finds angle of enemy relative to player in degrees
rb.rotation = angle;
direction.Normalize();
movement = direction;
}
private void FixedUpdate() {
moveCharacter(movement);
}
void moveCharacter(Vector2 direction) {
rb.MovePosition((Vector2)transform.position + (direction * moveSpeed * Time.deltaTime));
}
}
My enemy inspector:
My player inspector:
If anyone can find the problem, it would be a great help, thanks!
A few basics:
-
Imported models aren’t at the orientation you’d expect for a variety of reasons, but thats solved by making the imported model a child so you an offset it in position and rotation as you’d like. Can do it in math too but this is a simple answer to start.
-
Perhaps just add a rotation in code? I mean, there doesn’t seem to a bug here, just lack of extra support code to get the desired behaviour.
It’s probably just the disconnect between 3d package rotation and where the math defaults to.
How could i add that rotation then?
EDIT: I’ve done it:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyMovement : MonoBehaviour {
public Transform player;
private Rigidbody2D rb;
private Vector2 movement;
public float moveSpeed;
void Start() {
rb = this.GetComponent<Rigidbody2D>();
}
void Update() {
Vector3 direction = player.position - transform.position;
float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
rb.rotation = angle;
transform.LookAt(player.position);
transform.Rotate(new Vector3(0,90,0),Space.Self);
direction.Normalize();
movement = direction;
}
private void FixedUpdate() {
moveCharacter(movement);
}
void moveCharacter(Vector2 direction) {
rb.MovePosition((Vector2)transform.position + (direction * moveSpeed * Time.deltaTime));
}
}
Yep plenty of ways to handle it, and that’s one of many. Nice one. You just need to be expecting this sort of thing really, it’s not unusual 