0
\$\begingroup\$

I'm trying to switch the camera to another object on collision.

This is what I've tried to do:

    public Camera switchCamera1;
public GameObject player2;

private Vector3 offset;

void Start () {
    offset = transform.position - player2.transform.position;
}

void OnCollisionEnter (Collision col) {
    if (col.gameObject.name == "triggerCube") {
        //SceneManager.LoadScene ("test2");
        Debug.Log ("HIT SOMETHING");
        setWinText ();


        switchCamera1.transform.position = player2.transform.position + offset;


    }
}

However it simply doesn't work. I've set my camera to switchCamera1, I've set the other object to player2. The script is assigned to the collider object.

\$\endgroup\$
1
\$\begingroup\$

Are you perhaps forgetting to reparent the camera so it follows player2?

switchCamera1.transform.SetParent(player2.transform);

Not sure this is what you're after but perhaps a better explanation of the effect you're trying to achieve is required.

Hope that helps! :)

\$\endgroup\$
  • \$\begingroup\$ I tried removing the camera from the parent and I also tried your code but nothing works still. I'm having a collision in my game, where the camera follows object 1 into the collision. After the collision I want the camera to pan over to object 2, a few units away from the collision and follow that unit. \$\endgroup\$ – Paze Aug 23 '16 at 7:09
  • \$\begingroup\$ I see the problem tho, I have a camera script that keeps following object 1. Should I be writing this collision script in the original collision script or on the camera script? I dont know how to do it in the camera one. \$\endgroup\$ – Paze Aug 23 '16 at 7:16
1
\$\begingroup\$

Well, I'd suggest to use Smooth Follow script rather than making it child (if it is not particularly required).

  • You can grab the Camera Follow code from this answer

  • Attach it to your camera (please un-child your camera first)

  • Drop the initial target in Target in just attached Smooth Follow script.

  • Access this script in your current script in which you want to play with it. (By public SmoothFollow smoothFollw; or by FindObjectOfType< SmoothFollow>() whatever you want)

  • Now change the target on collision by changing its target transform value.

Hope this helps.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.