- Home /
Player moves to the middle of the room when the level starts (2d point and click)
Hi! I am new to Unity and I found this script online for moving the player using mouse input. But every time the level starts the player moves to the center of the scene. I'm not sure how to keep it where I placed it during setup. Please help! (Unity 2018.2.7f1, 2D) My code:
public class MovePlayer2 : MonoBehaviour {
public Vector2 targetPosition;
[SerializeField]
private Rigidbody2D rb;
[SerializeField]
private float speed = 10;
// Update is called once per frame
void FixedUpdate () {
if(Input.GetMouseButtonDown(0)) { //checks that the left mouse button has been pressed
targetPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition); //sets the targetPosition to the dimensional point in the game where the mouse clicked
}
transform.position = Vector2.MoveTowards(transform.position, targetPosition, Time.deltaTime * speed); //it will move from the current position to the target position and the time.deltaTime
}
}
Answer by sean244 · Feb 03, 2019 at 01:15 AM
Just re-write your code to the following:
using UnityEngine;
public class MovePlayer2 : MonoBehaviour
{
public Vector2 targetPosition;
private Rigidbody2D rb;
[SerializeField]
private float speed = 10;
private void Start()
{
rb = GetComponent<Rigidbody2D>();
}
private void Update()
{
if (Input.GetMouseButtonDown(0))
{
targetPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
}
}
private void FixedUpdate()
{
if (targetPosition.magnitude > 0)
{
var position = Vector2.MoveTowards(transform.position, targetPosition, Time.deltaTime * speed);
rb.MovePosition(position);
}
}
}
You’re welcome. Please subscribe to my YouTube channel https://www.youtube.com/channel/UCo_3O$$anonymous$$EZQiRLQihycbkYd_Q
Answer by CBlockSurprise · Feb 02, 2019 at 11:22 PM
You need to set the transform of the player's to an empty gameObject
[SerializeField]
private Transform spawn;
void Start () {
transform.position = spawn.position;
}
So 1. make an empty gameObject. 2. make it the parent of the player. 3. Add this code. ?
$$anonymous$$ake an empty gameObject, then position it where you need the player to start out. Add the code and set the private transform to the empty gameObject.
Don't parent it, or the spawn point will move with the player
Your answer
Follow this Question
Related Questions
Making a bubble level (not a game but work tool) 1 Answer
Sprite will not roate when arrow keys are pressed 2 Answers
How to know if my player is not moving? 2 Answers
Movement Problems PS4 Controller 0 Answers