Search Unity

Question Drag and Drop by mouse?

Discussion in 'Physics for ECS' started by DinHammer, May 24, 2021.

  1. DinHammer

    DinHammer

    Joined:
    Sep 9, 2018
    Posts:
    7
    Please share an example of how to drag and drop an element using DOTS physics by mouse.
    I saw an example from the unity repository, how to do it without a spring.
     
  2. petarmHavok

    petarmHavok

    Joined:
    Nov 20, 2018
    Posts:
    461
    The spring makes it much harder than regular drag and drop. Just go to MousePickSystem, locate the Pick job, and edit the if (CollisionWorld.CastRay()...) to only set the position of the hit body to the mouse position. And that's it.
     
    steveeHavok likes this.
  3. DinHammer

    DinHammer

    Joined:
    Sep 9, 2018
    Posts:
    7
    Please show this in the code
     
  4. steveeHavok

    steveeHavok

    Joined:
    Mar 19, 2019
    Posts:
    481
    The Mouse Pick is active in every scene in the samples project and the associated script is here.
     
  5. DinHammer

    DinHammer

    Joined:
    Sep 9, 2018
    Posts:
    7
    I found the script. I do not understand how and where to change the coordinate of the Entity by Mouse, so I ask for an example
     
  6. steveeHavok

    steveeHavok

    Joined:
    Mar 19, 2019
    Posts:
    481
    Are you asking about Line 285?
    Code (CSharp):
    1. float3 pointSpringWs = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, springData.MouseDepth));
    2.  
    With an old position and the new position you can tweak the MouseSpringSystem to do whatever you need with the displacement.
    Code (CSharp):
    1. float3 displacement = pointBodyWs - pointSpringWs;
    2. var newPosition = Positions[entity] + displacement;
    Like set position:
    Code (CSharp):
    1. Positions[entity] = new Translation() { Value = newPosition };
    or
    Code (CSharp):
    1. var position = Positions[entity];
    2. var rotation = Rotations[entity];
    3. var velocity = Velocities[entity];
    4. var target = new RigidTransform(rotation.Value, newPosition);
    5. velocity.CalculateVelocityToTarget(Masses[entity], position, rotation, target, math.rcp(Time.DeltaTime));
    6. Velocities[entity] = velocity;
    Actually, I am a little confused as to what you are asking this for. You originally asked "how to do it without a spring.".
    Just moving a body by changing the Entities
    Translation
    component, rather than via the
    PhysicsVelocity
    component, violates the Physics simulation and is usually a bad idea.
    Alternatively, the CalculateVelocityToTarget function available on the PhysicsVelocity struct, can have equally violent results.

    Are you dealing with Dynamic bodies or Kinematic bodies? What is your use case?
     
    Occuros likes this.