简体   繁体   中英

how do i add force in the direction the player is facing

So the code is on a object that makes the player bounce and it gets the rb and adds a force that makes it go up but I would like it also to give the player a boost in the direction their facing.

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

public class bounce : MonoBehaviour
{
    [Range(100, 10000)]
    public float bouncehight;

    [Range(100, 10000)]
    public float boost;

    private void OnCollisionEnter(Collision collision)
    {
        GameObject bouncer = collision.gameObject;
        Rigidbody rb = bouncer.GetComponent<Rigidbody>();

        rb.AddForce(Vector3.up * bouncehight);

        //so here i would call or something 

        rb.AddForce(Vector3.forward * boost *look);


    }

You can get the direction vector of a GameObject viaTransform.forward .

This would probably be something like rb.AddForce(transform.forward * boost)

Easiest way would be to use transform.forward:

rb.AddForce(transform.forward * forceAmount)

Alternatively you can count it yourself for the same result:

rb.AddForce(Vector3.forward * transform.rotation * forceAmount)

Edit: since you are inside bounce class transform.forward refers to the bounce, hence always the same direction. Use rb.gameObject:

rb.AddForce(Vector3.forward * rb.gameObject.transform.rotation * forceAmount)

Or

  rb.AddForce(rb.gameObject.transform.forward * forceAmount)

to refer to the player's rotation instead

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM