Moving camera with player in 2d

Hi

I’m new to unity and I’m trying to write a script for my camera move my it with the player object. Hoever, I found I cannot use the “transform.player” because unity can’t recognize player as a Ridgidbody2D with position for some reason. Someone might see how I solve this, i.e. getting hold of the player position?

using UnityEngine;
using System.Collections;

public class Camerafollow : MonoBehaviour
{




		// Use this for initialization
		void Start ()
		{
	
		}
	
		// Update is called once per frame
		void Update ()
		{
		Rigidbody2D player = Instantiate(GameObject.Find ("Player")) as Rigidbody2D;
		Vector2 hastighet = player.velocity;
		if (hastighet !=  0) {
			Vector2 playerpos;
			playerpos.x = transform.player;
			playerpos.y = transform.player;
			transform.position = playerpos;
				}
				
		}
}

2 Answers

2

Instantiate() creates a new player, so your code is creating a new player every frame. What you want to do is get a reference to the player in Start(), then use that reference to position the camera. Something like:

using UnityEngine;
using System.Collections;

public class Camerafollow : MonoBehaviour {

	private Transform player;

	void Start () {
		player = GameObject.Find ("Player").transform;
	}
	
	void Update () {
		Vector3 playerpos = player.position;
		playerpos.z = transform.position.z;
		transform.position = playerpos;
	}
}

Thanks, that helped alot.

Thank you that worked perfectly. I noticed the behavior seemed to be the same when the camera is a child to the player object. Is that correct?

You should ask this as a new question, not as a 'Solution' to an existing question. As for the error, you need to do: if (Finnpos.x >= transform.position.x) Vector3 v = transform.position; v.x = Finnpos.x; transform.position = v; } But this snipped does not take a look at the larger tracking issue, only solves the compiler error.

Tested and worked!!! Sorry for my english.

1 - Create an Game Object with name “Player”

2 - Create an Game Object with name “Boundary Markers”

2.1 - Create a game object with name “Left Marker” into Boundary Markers

2.2 - Create a game object with name “Right Marker” (and change a Transform position x for 25 Right Markers’s ) into Boundary Markers

3 - Create script “Camera Follow”

using UnityEngine;
using System.Collections;

**public class CameraFollow : MonoBehaviour {

public Transform player;
public Transform farLeft;
public Transform farRight;
void Update () {

	Vector3 newPosition = transform.position;
	newPosition.x = player.position.x;
	newPosition.x = Mathf.Clamp(newPosition.x, farLeft.position.x, farRight.position.x);
	transform.position = newPosition;
}

}**

4 - Attached Game Object Player on player

5 - Attached Game Object Left Marker on farLeft

6 - Attached Game Object Right Marker on farRight

For more informations:
http://unity3d.com/pt/learn/tutorials/modules/beginner/live-training-archive/making-angry-birds-style-game-pt2