I have a question that is kind of basic. I need to access the position of “Spelaren” which is the main player, a Rigidbody2D. However, I can’t find a way to get the position vector for the player. “transform.Spelaren” is not applicable and I would like to know how to do it. Anyone?
using UnityEngine;
using System.Collections;
public class Kameraflytt : MonoBehaviour
{
// Use this for initialization
void Start ()
{
}
// Update is called once per frame
void Update ()
{
Rigidbody2D Spelaren = Instantiate(GameObject.Find ("Spelaren")) as Rigidbody2D;
Vector2 hastighet = Spelaren.velocity;
if (hastighet != 0) {
Vector2 Spelarpos;
Spelarpos.x = transform.Spelaren;
Spelarpos.y = transform.Spelaren;
transform.position = Spelarpos;
}
}
}
transform.postition = new Vector2(Spelarpos.gameobject.transform.position.x, Spelarpos.gameobject.transform.position.y);
If I understood correctly what are you trying to achieve.
Another point: you should not Instantiate objects that you “Find” in your scene. Currently your code instantiates new Rigidbody2D which is a copy of object found in the scene which is bad for performance. Also consider instantiating a prefab instead of an object that you found in your scene (which you are currently doing). Find main player in Awake() or Start() and cache it.
transform.position.x and transform.position.y, not transform.Spelaren.
You’re already doing it correctly on the next line.
I am not sure I understand your code correctly… but I would advice to instantiate the prefab as Gameobject and then accessing the transform as child of it.
But it seems you already have the player character “Spelaren” in your scene, so this code should work:
Gameobject player;
Rigidbody2D player_rb;
Vector2 tmp_pos;
void Start()
{
player = GameObject.Find("Spelaren");
player_rb = player.GetComponent<Rigidbody2D>();
}
void Update ()
{
Vector2 hastighet = player_rb.velocity;
if (hastighet != 0) {
tmp_pos.x = player.transform.position.x;
tmp_pos.y = player.transform.position.y;
transform.position = tmp_pos;
}
}
(This code hasn’t been tested, I just wrote it off the top of my head)