0
\$\begingroup\$

I have a player with rigidbody and it has a tag as Player .

enter image description here

I have set a sphere collider as trigger with script

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

public class Addforce : MonoBehaviour {

public int speed;

void OnCollisionEnter(Collision other)
{
    if (other.gameObject.CompareTag("Player"))
    {
        other.gameObject.GetComponent<Rigidbody>().AddForce(Vector3.up*speed);
    }
}

}

I have set speed force to 100.

But when player enters the collider, nothing happens. It doesn't tag it.

\$\endgroup\$
2
  • \$\begingroup\$ Please post the script code as code and not as a screenshot. \$\endgroup\$
    – Galandil
    Mar 19, 2018 at 21:51
  • \$\begingroup\$ I see you have a Rigidbody First Person Controller script attached. It's possible that this is overriding the physics inputs from other sources. Can you share some details of this script? \$\endgroup\$
    – DMGregory
    Mar 19, 2018 at 22:22

1 Answer 1

1
\$\begingroup\$

Since the sphere is a trigger, you need to use OnTriggerEnter(Collider other) instead of OnCollisionEnter.

OnCollisionEnter, OnCollisionExit and OnCollisionStay are called when both objects' colliders are not triggers.

Moreover, you should specify that the force added is an impulse. You should do this:

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

public class Addforce : MonoBehaviour {

    public int speed;

    void OnTriggerEnter(Collider other)
    {
        if (other.gameObject.CompareTag("Player"))
        {
            other.gameObject.GetComponent<Rigidbody>().AddForce(Vector3.up*speed, ForceMode.Impulse);
        }
    }
}
\$\endgroup\$
10
  • \$\begingroup\$ Still doesn't apply force on player if I change OnTriggerEnter. \$\endgroup\$
    – Wildfire
    Mar 19, 2018 at 21:59
  • \$\begingroup\$ Yes, addforce script is attached to green cuboid with sphere collider as trigger. \$\endgroup\$
    – Wildfire
    Mar 19, 2018 at 22:05
  • \$\begingroup\$ Galandil, now it does work . But I had to uncheck IsTrigger on sphere collider. How to add an angle to the force? About 45 degrees. \$\endgroup\$
    – Wildfire
    Mar 19, 2018 at 22:26
  • \$\begingroup\$ @Wildfire why you had to uncheck isTrigger? OnTriggerEnter would never fire if both objects are not a trigger. \$\endgroup\$
    – Galandil
    Mar 19, 2018 at 22:28
  • \$\begingroup\$ Otherwise, it does not work if I check IsTrigger on sphere collider. Player just walks on the collider. \$\endgroup\$
    – Wildfire
    Mar 19, 2018 at 22:32

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .