1

i can't figure out how to check for collision, here is my camera-movement script:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class cameracontroller : MonoBehaviour
{   


public float movementSpeed;
public float movementTime;

public Vector3 newPosition;
// Start is called before the first frame update
void Start()
{
    newPosition = transform.position;
}

// Update is called once per frame
void Update()
{
    HandleMovementInput();
}


void HandleMovementInput()
{
    
    if(Input.GetKey(KeyCode.W))
    {
        newPosition += (transform.forward * movementSpeed);
    }
    
    if(Input.GetKey(KeyCode.S))
    {
        newPosition += (transform.forward * -movementSpeed);
    }
    
    if(Input.GetKey(KeyCode.D))
    {
        newPosition += (transform.right * movementSpeed);
    }
    
    if(Input.GetKey(KeyCode.A))
    {
        newPosition += (transform.right * -movementSpeed);
    }
    
    transform.position = Vector3.Lerp(transform.position, newPosition, Time.deltaTime * movementTime);
    }

}

I've tried using void OnCollisionEnter(Collision collision) but didn't seem to work, am i doing something wrong? All object have colliders and i have also tried using rigidbody. I am still a beginner programmer and only code in my spare time, to explain my lack of knowledge.

Ruzihm
  • 19,749
  • 5
  • 36
  • 48
  • Does this answer your question? [Collision detection not working unity](https://stackoverflow.com/questions/43939179/collision-detection-not-working-unity) – Ruzihm Sep 02 '20 at 19:59

1 Answers1

0

OnCollisionEnter is a bit tricky, I believe you get the best result with it when it is interacting with dynamic Rigidbodies (i.e not kinematic). If you want it to check for collision with say walls, in which case neither the camera nor the walls have dynamic rigidbodies, then just use OnTriggerEnter.

If you're trying to make a RPG styled character controller and the camera collision code is to help prevent camera clipping through walls, then I believe you can get the job down with raycast (by shooting a raycast from camera towards the player) instead of using OnTrigger.

SirMt
  • 38
  • 5