I want to see if the random location is ray.

Asked 1 years ago, Updated 1 years ago, 40 views

I threw up an error and it doesn't work. The error is as follows.

 error CS0120: An object reference is required for the non-static field, method, or property 'raycast.movePosition'

How can I move?If it moves again, will it work correctly?

public class raycast:MonoBehavior
{
    Vector3 movePosition; 

    void Start()
    {
        movePosition=moveRandomPosition();  
    }
    public class test —MonoBehavior
    {

        void Update()
        {
            Ray=movePosition;

            RaycastHit;
            if(Physics.Raycast(ray,outhit,10.0f))
            {
                Debug.Log(hit.collider.gameObject.transform.position);
            }
            Debug.DrawRay (ray.origin, ray.direction*10, Color.red, 5);
            movePosition=moveRandomPosition();
        }
    }
    private Vector 3 moveRandomPosition() 
    {
        Vector3 randomPosi = new Vector3 (Random.Range (-7, 7), Random.Range (0, 0), Random.Range (-7, 7);
        return randomPosi;
    }

unity3d

2022-09-30 14:00

1 Answers

If you want to hang around like this,

Wonder.gif

You can do it with this code.

using System.Collections;
using UnityEngine;

public class RayTest —MonoBehavior
{
    SerializeField float_moveSpeed=1.0f;
    SerializeField float_rayLength=5.0f;
    Vector3_destination=default;

    void Start()
    {
        MoveToRandomDestination();
    }

    void Update()
    {
        Ray = new Ray (this.transform.position, _destination-this.transform.position);
        Debug.DrawRay(ray.origin,ray.direction*_rayLength,Color.red);

        if(Physics.Raycast(ray, out RaycastHit,_rayLength))
        {
            Detected Debug.Log($"{hit.collider.name}.");
            MoveToRandomDestination();
        }
    }

    void MoveToRandomDestination()
    {
        StopAllCoroutines();
        _destination=
            new Vector 3 (Random.Range (-7,7), 0, Random.Range (-7,7));
        Debug.DrawLine(_destination,_destination+Vector3.up, Color.green, 3f);
        StartCoroutine (MoveToDestination());
    }

    IEnumerator MoveToDestination()
    {
        Vector3 direction=_destination-this.transform.position;

        while(Vector3.Distance(this.transform.position,_destination)>_rayLength)
        {
            This.transform.Translate(direction.normalized*_moveSpeed*Time.deltaTime);
            yield return null;
        }

        Debug.Log("Destination Arrived");
        MoveToRandomDestination();
    }
}

Also leave the unitypackage.


2022-09-30 14:00

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.