2

I have a script that projects a ray to the ground layer from the mouse to show where an object is about to be placed. Its a city builder thats supposed to show an outline of a house before its placed. The outline is just a prefab with a transparent material.

When the prefab is moving with the mouse (about to be placed) it shakes about and I can't figure out why. Anyone know how to fix this?

Also layer 8 is the ground.

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

public class BlueprintScript : MonoBehaviour
{   
    RaycastHit hit;
    Vector3 movePoint;
    public GameObject prefab;
 
    void Start()
    {
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        if(Physics.Raycast(ray, out hit, 50000.0f, (1 << 8)))
        {
             transform.position = hit.point;
        }
    }

    void Update()
    {
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
     
        if (Physics.Raycast(ray, out hit, 50000.0f, (1 << 8)))
        {
              transform.position = hit.point;
        }

        if (Input.GetMouseButton(0))
        {
              Instantiate(prefab, transform.position, transform.rotation);
              Destroy(gameObject);
        }
    }
}
Ruzihm
  • 19,749
  • 5
  • 36
  • 48

1 Answers1

0

Try following:

  • Disable your outlined house colliders (if any). (If it works well now, then probably your ray was hitting the outlined house.)

  • Print the hit.point and see if it really has a jitter.

  • If there was a jitter, make sure your camera is not moving.

  • Replace Update with FixedUpdate. You better do your physics processions in a FixedUpdate method. (And check your input events in Update method separately.)

  • If it's still jittering, review your physics settings and finally add a Vector3.Lerp for your transform.position assignment.

    transform.position = Vector3.Lerp(transform.position, hit.point, 0.07F);

I think the fourth one is your answer, good luck.

Bamdad
  • 726
  • 1
  • 11
  • 28