How can i make a sprite face and move to my cursor?
I am making a top-down shooter game, and encountered this problem early on while making a playerMovement script. I'm trying to get the sprite to always face the mouse cursor and move in that direction when "w" is pressed. Here is my current script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class playerController : MonoBehaviour {
public Rigidbody2D rb;
public float speed;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
var dir = Input.mousePosition - Camera.main.WorldToScreenPoint (transform.position);
var angle = Mathf.Atan2 (dir.y, dir.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.AngleAxis (angle, Vector3.forward);
if (Input.GetKey ("w"))
{
rb.AddForce (Vector3.up * speed * Time.deltaTime);
}
}
}
Answer by monkaS98 · Dec 10, 2018 at 11:02 PM
Hi @OceKat3,
I've edited your script a bit, try to use it in your game. Also I'm a bit noob in coding so not sure if it is what you want in your game.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class playerController : MonoBehaviour {
public Rigidbody2D rb;
public float speed;
//this variable to control the direction of your sprite
//try to adjust this variable until you find the best one
public int rotationOffset = 90;
//it's generally a good idea to use FixedUpdate instead of Update if you
//are going to mess with physics
void FixedUpdate()
{
var dir = Input.mousePosition - Camera.main.WorldToScreenPoint(transform.position);
var angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(0f, 0f, angle + rotationOffset);
if (Input.GetKey("w"))
{
//here I've edited your script and added raycast to get the position of the mouse on screen
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
Plane plane = new Plane(Vector3.forward, transform.position);
float dist = 0;
if (plane.Raycast(ray, out dist))
{
Vector3 pos = ray.GetPoint(dist);
rb.AddForce(pos * speed * Time.deltaTime);
}
}
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612183629im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
2D Object following the cursor without glitchyness at the center 0 Answers
Can't get object to destroy itself on collision. 0 Answers
Player not moving 1 Answer
I cant get 2D collisions to work, but everything looks ok to me, any help please? 4 Answers
How to detect if ObjectA is looking at ObjectB, and vice versa? 2 Answers