Fables Alive
Fables Alive

Reputation: 2798

getClosestPoint from the mouse-cursor position to first object that hits of the raycast (maya mel script)

researching for getting a worldpoint from the mouse-cursor position to first object that hits of the raycast. maybe an api func getClosestPoint or rayIntersect can do that job ?if so how? (thank you)

Upvotes: 2

Views: 3224

Answers (2)

Tomek
Tomek

Reputation: 121

I've found this piece of code, but I'm not exactly sure who wrote it. Anyway, this might be what you're looking for.

import maya.OpenMaya as om
import maya.OpenMayaUI as omui
import maya.cmds as cmds

ctx = 'myCtx'

def onPress():
    vpX, vpY, _ = cmds.draggerContext(ctx, query=True, anchorPoint=True)
    print(vpX, vpY)

    pos = om.MPoint()
    dir = om.MVector()
    hitpoint = om.MFloatPoint()
    omui.M3dView().active3dView().viewToWorld(int(vpX), int(vpY), pos, dir)
    pos2 = om.MFloatPoint(pos.x, pos.y, pos.z)
    for mesh in cmds.ls(type='mesh'):
        selectionList = om.MSelectionList()
        selectionList.add(mesh)
        dagPath = om.MDagPath()
        selectionList.getDagPath(0, dagPath)
        fnMesh = om.MFnMesh(dagPath)
        intersection = fnMesh.closestIntersection(
        om.MFloatPoint(pos2),
        om.MFloatVector(dir),
        None,
        None,
        False,
        om.MSpace.kWorld,
        99999,
        False,
        None,
        hitpoint,
        None,
        None,
        None,
        None,
        None)
        if intersection:
            x = hitpoint.x
            y = hitpoint.y
            z = hitpoint.z
            cmds.spaceLocator(p=(x,y,z))


if cmds.draggerContext(ctx, exists=True):
    cmds.deleteUI(ctx)
cmds.draggerContext(ctx, pressCommand=onPress, name=ctx, cursor='crossHair')
cmds.setToolTo(ctx)

Upvotes: 4

Julian Mann
Julian Mann

Reputation: 6466

You can do this in either MEL or python using the autoPlace command with the useMouse flag set to true.

float $pos[] = `autoPlace -um`;

It will fire a ray from the mouse cursor to the live surface Use the makeLive command to make a surface live in a script.

You could write a tool context so that when you enter it, the selected surface becomes live, then you click on it and do something with the result (like place a locator), then deselect the object and makeLive again to reset the grid to be live.

Upvotes: 2

Related Questions