transform.Translate but with raycast distance

Hi.
i wanna move a point using transform Translate:

_objectToPlaceRoot.transform.Translate(_camera.transform.right * _input.x, Space.World);
_objectToPlaceRoot.transform.Translate(Vector3.up * _input.y, Space.World);

but also changing its Y position (height) based on a raycast at the same time

if (Physics.Raycast(from, dir, out RaycastHit hit, Mathf.Infinity, _treeLayer))
{     
  hitpoint = hit.point;
}

i thought i can simply do it this way after the transform translate code

 _objectToPlaceRoot.transform.position = new Vector3(_objectToPlaceRoot.transform.position.x, hitpoint.y, _objectToPlaceRoot.transform.position.z);

but the _objectToPlaceroot is just somewhere else in the world now.
how am i supposed to do that the right way?
thanks

The issue here is Transform.Translate takes a direction, while Transform.position takes a… position.

So you need to make both play nice just one one or the other. The easiest at a glance at your code would be to work with positions.

Generally it’s best to build a vector and use it right at the end. So you can first get the horizontal position offset from input (current position + input), the vertical position from your raycast, put those together and set the transform’s position to that.

2 Likes

hey, thanks, i tried to do it this way now:

Vector3 right = _camera.transform.right * _input.x;
Vector3 up = _camera.transform.up * _input.y;
              
Vector3 forward = Vector3.zero;
_objectToPlaceRoot.transform.position += right + up + forward;

so that works just like transform translate for moving left/right/up down

but i dont really know what to set for the forward.
so thats where the raycast hit something, so that the forward distance should match the raycast distance

What exactly is ‘forward’ in this context? I’m not sure what type of movement we’re dealing with here.

Screenshots may help.

Admittedly still trying to understand you a bit. So you can move the box up/down/left/right, but want it to remain in front of the tree based on a raycast from the camera?

I guess that gets a little complicated. I guess you maintain a position of where the box currently is, and if you register a raycast hit, subtract the position of the hit from the box.