Search code examples
c#unity-game-engineclamp

unity3d - how to clamp x axis from gameobject transform forward perspective?


i moved object according mouse position with ray cast ,i would like to know how i can clamp in any given position and rotation the object x axis that relative to transform forward of the object? , not generally relative to the world any ideas? , thanks in advance. the code below shows the basic how i implement object movement according the mouse position now i want to clamp it

 Ray ray = mainCamera.ScreenPointToRay(Input.mousePosition);
 
    plane = new Plane(Vector3.up, transform.position);
    float enter;
        if(plane.Raycast(ray,out enter))
        {
            hitPoint = ray.GetPoint(enter);
            transform.position = hitPoint;
        }

Solution

  • If I understand you correctly what you are trying to achieve is to move your object only on its local x-axis.

    And do something like this (behold my amazing paint skills)

    enter image description here

    You can use Vector3.Project to achieve that like e.g.

    var ray = mainCamera.ScreenPointToRay(Input.mousePosition);
    var plane = new Plane(Vector3.up, transform.position);
    
    if(plane.Raycast(ray, out var enter))
    {
        var hitPoint = ray.GetPoint(enter);
    
        var actualPositionDelta = hitPoint - transform.position;
        var mappedPositionDelta = Vector3.Project(actualPositionDelta, transform.right);
    
        transform.position += mappedPositionDelta;
    }