Unity raycast with different behavior between editor and build
I am trying to build a curved mesh in Unity. The idea is to put all of the GameObject on a sphere and show the sphere from the inside.
I did it without any problems with a render texture (1500*1500) generated by a camera on a canvas. It works as expected.
However, as you can guess, the events are not working since the canvas creating the render texture is the one handling the events, not the texture itself.
To fix this issue, I created a script that translates the coordinates on the sphere in coordinates in the canvas and send the event to the right GameObject using a raycaster.
eventSystem.RaycastAll(computedPosition, raycastList);
var raycast = FindFirstRaycast(raycastList);
This code allows me to propagate the event to the GameObject on the canvas. And it works perfectly.
Everything works exactly as I want when I start the game in the editor. But, and I can't understand why, when I build the project and start the game, it doesn't work.
I made a few comparisons between the built game and the game in the editor:
- The positions of all the components are exactly the same
- The computed positions on the canvas are the same, regardless of the resolution
- In the built game, all the components with a computed Y value higher than 1080 are working fine
- In the built game, all the components with a computed Y value lower than 1080 are not working
When I say "not working", I mean that this function
eventSystem.RaycastAll(computedEvent, raycastList);
is returning an empty list. The raycast can't find any game object in build mode while it was able to do so in editor mode.
My first guess was unity removes the elements from the screen, if they look useless, for optimizations. But it doesn't seem to be the case.
My question is why is there a different behavior? Did I miss something? I suppose the 1080 value is quite important, but I can't find any relationship with it.
See also questions close to this topic
-
read Smart quotes from PDF in data variable using C#
I am working with Blue prism, I am using c# code stage to read the PDF using itextfile dll, I get all the text except the smart quotes text for example “the Bank”. How can I read this all text including smart quotes in string variable?
-
Verificator.Verify() Exception from HRESULT: 0xFFFFFFF8
i am really stuck to verify fingerprint from database. and try many thinks. any body help me where i am wrong
Database Field (I tried to change datatype Binary(1632) and Image) I try to save four fingers
Finger1 varbinary(MAX)
Finger2 varbinary(MAX)
Save fingerprint
public byte[] ImageToByteArray(Image img) { MemoryStream ms = new System.IO.MemoryStream(); if (img != null) img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); return ms.ToArray(); }
Verify fingerprint
foreach (DataRow dr in dt.Rows) { byte[] _img = (byte[])dr["Finger1"]; MemoryStream ms = new MemoryStream(_img); Template Template = new Template(); Template.DeSerialize(ms); DPFP.Verification.Verification Verificator = new DPFP.Verification.Verification(); FeatureSet features = ExtractFeatures(Sample, DPFP.Processing.DataPurpose.Verification); if (features != null) { DPFP.Verification.Verification.Result result = new DPFP.Verification.Verification.Result(); Verificator.Verify(features, Template, ref result); if (result.Verified) MessageBox.Show("The fingerprint was VERIFIED."); else MessageBox.Show("The fingerprint was NOT VERIFIED."); } }
Exception Text
DPFP.Error.SDKException: Event Handler has generated an Exception ---> System.Runtime.InteropServices.COMException: Exception from HRESULT: 0xFFFFFFF8
at DPFP.Verification.Verification.MC_verifyFeaturesEx(SafeHandle mcContext, Int32 templateSize, Byte[] templatePt, Int32 featureSetSize, Byte[] featureSet, Int32 reserved0, IntPtr reserved1, IntPtr reserved2, IntPtr reserved3, Double& achievedFar) at DPFP.Verification.Verification.Verify(FeatureSet FeatureSet, Template Template, Int32 FARRequested) at DPFP.Verification.Verification.Verify(FeatureSet FeatureSet, Template Template, Result& Result) at MACS.frmMain.OnComplete(Object Capture, String ReaderSerialNumber, Sample Sample) in C:\Workstation\Projects\Client Projects\MACS\MACS\frmMain.cs:line 242 at DPFP.Capture.Capture.MessageReceived(Message& m) --- End of inner exception stack trace --- at DPFP.Error.ExceptionFactory.Throw(Exception Exception, ErrorCodes ErrorCode, String ErrorMessage) at DPFP.Capture.Capture.MessageReceived(Message& m) at DPFP.Capture.Capture.MessageEvents.MessageWindow.WndProc(Message& m)
-
Authorize attribute always ignored in ASP.net core Web API
I signed up on Auth0 and walked through the tutorial to add authorization/authentication to a sample asp.net core WebAPI app.
Problem
When sending a request via PostMan to that API (PostMan and asp.net core app in Docker running locally) then I get return code
200
. I would expect401
because I didn't set any authorization header in the request.Code
public void ConfigureServices(IServiceCollection services) { services.AddScoped<BookService>(); services.AddScoped<ProjectService>(); services.AddScoped<UserService>(); services.AddMvc(); string domain = $"https://{Configuration["Auth0:Domain"]}/"; services.AddAuthentication(options => { options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }).AddJwtBearer(options => { options.Authority = domain; options.Audience = Configuration["Auth0:ApiIdentifier"]; }); services.AddAuthorization(options => { options.AddPolicy("update:subscription", policy => policy.Requirements.Add(new HasScopeRequirement("update:subscription", domain))); }); services.AddSingleton<IAuthorizationHandler, HasScopeHandler>(); } public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseAuthentication(); app.UseMvc(); }
Controller with HTTP Post route
[Route("api/[controller]")] public class SubscriptionController : ControllerBase { ... [HttpPost] [Authorize] public string SubscriptionUpdate([FromBody] Subscription subscription) { ... } }
I tried with and without the policy based authorization.
Question
How can I make sure that JWT bearer based authentication is not ignored for that aspnet core WebAPI app?
-
How to get vuforia cloud recognition kind of feature in Arcore(unity)
I have created a prototype application in unity using vuforia where I upload an image to myserver the server then sends the image (and associated assetbundle's link in metadata) to vuforia cloud to add it to the image target database. then in unity when camera tracks the image target I download the asset bundle to augment it.
public void OnNewSearchResult(TargetFinder.TargetSearchResult targetSearchResult) { TargetFinder.TargetSearchResult cloudRecoSearchResult = (TargetFinder.TargetSearchResult)targetSearchResult; mTargetMetadata = cloudRecoSearchResult.MetaData; Debug.Log(mTargetMetadata); mCloudRecoBehaviour.CloudRecoEnabled = false; // Build augmentation based on target if (ImageTargetTemplate) { Debug.Log("Image target activated"); // enable the new result with the same ImageTargetBehaviour: ObjectTracker tracker = TrackerManager.Instance.GetTracker<ObjectTracker>(); ImageTargetBehaviour imageTargetBehaviour = (ImageTargetBehaviour)tracker.TargetFinder.EnableTracking( targetSearchResult, ImageTargetTemplate.gameObject); JsonData jd = JsonMapper.ToObject(mTargetMetadata); string url = jd["content-url"].ToString(); Debug.Log("video url :"+ "http://192.168.2.92/arads/" + url); vidPlayer.url = "http://192.168.2.92/arads/"+url; vidPlayer.Prepare(); if(!vidPlayer.isPlaying) vidPlayer.Play(); } }
the above code is to get associated video from the server. Can I get similar functionality with arcore or arfoundation, I read that arcore's refrence image database can have 1000 images,
what if the image I am tracking is not in the current database, can I switch to different db in that case ?
do I have to download and add the image to database in the applicatoin whenever I upload a new image on the server ?
can these images in arcore have meta data like in vuforia ?
-
Is it possible to resize Hand based on real hands using Leap Motion in Unity?
I want to resize my hand size in VR based on my real hand size.
I am using Leap Motion SDK and rigged hand in Unity.
Hand which I am using : https://assetstore.unity.com/packages/3d/characters/humanoids/leap-motion-realistic-hands-109961
Any suggestion?
-
Why is a comparison in my if statement effecting the output
I am trying to add a jump function into my game and the 3rd part my if statement is affecting how high the jump is instead making sure you jump under. Like if I put 2 instead of 1.001f it will jump high but if it's 1.1 it barely jumps. Also, 1.001 doesn't seem to work at all.
public float jumpForce = 300f;
This code has no jump
if (Input.GetKey("space") && rb.position.y < 1.001f) { rb.AddForce(0, jumpForce * Time.deltaTime, 0, ForceMode.VelocityChange); }
This code does a little jump
if (Input.GetKey("space") && rb.position.y < 1.1f) { rb.AddForce(0, jumpForce * Time.deltaTime, 0, ForceMode.VelocityChange); }
And this code does a high jump
if (Input.GetKey("space") && rb.position.y < 2f) { rb.AddForce(0, jumpForce * Time.deltaTime, 0, ForceMode.VelocityChange); }
-
Return true if object is closer than a value. (Speherasting) in Unity
I have a script, for example, attached to a fire and I want to make damage to a player if he gets closer than a value to this fire.
public float fireDamageRange = 5; public float fireDamage = 10; private Vector3 origin; private Vector3 direction; void Update(){ origin = transform.position; direction = transform.forward; RaycastHit fireHit; if (Physics.SphereCast(origin, fireDamageRange, direction, out fireHit) && fireHit.transform.gameObject.layer == LayerMask.NameToLayer("Player") && !makingDamage) { makingDamage = true; MakeDamage(fireHit); StartCoroutine(WaitToMakeDamage()); } } IEnumerator WaitToMakeDamage() { yield return new WaitForSecondsRealtime(0.2f); makingDamage = false; }
The script is attached to the fire. This only returns true if the Player is actually fireDamageRange away of the origin, not if he gets closer. What am I doing wrong?
-
Raycasting works only on one half of an object
The goal of is to trace the inner outline of an obj. and extrude that outline into a new shape. The raycasting starts in the middle of the world (0,0,0) with the obj. placed around it.
file:///D:/Mach%20Parat/raycasting/raycast_stackoverflow/raycast.html
The red lines are the visualized directions of the rays. Everytime the rays intersect with the object, the coordinates are put into an array - based on that array, the yellow extrude-object is generated.
Problem is that only half of the rays seem to register hitting the obj.
The obj. is a teapot generated in Blender - The cup is half-full I guess. https://images-wixmp-ed30a86b8c4ca887773594c2.wixmp.com/intermediary/f/8a5fae76-ef7d-4795-9d79-f9b354b893db/dcz4o34-80b02357-3fec-469a-b290-00103f83f4ba.png
Using a simple object like a sphere (default object in Blender) works fine: https://images-wixmp-ed30a86b8c4ca887773594c2.wixmp.com/intermediary/f/8a5fae76-ef7d-4795-9d79-f9b354b893db/dcz4o2r-19c407a3-7b1d-458c-b39a-61189839a044.png
But only so long as the object is centered (0,0,0). Move it a few pixels and the same problem occurs: https://images-wixmp-ed30a86b8c4ca887773594c2.wixmp.com/intermediary/f/8a5fae76-ef7d-4795-9d79-f9b354b893db/dcz4o2l-2c6a17f8-e3a4-464e-a022-151839581355.png
it's up for download here, if you want to check for yourself: http://download.mach-parat.de/raycast.zip
//////////////////////// Model var model= "models/teapot.obj"; addObject(model); } function addObject (model){ var loader = new THREE.OBJLoader(); loader.load( model, function ( object ) { console.log("load"); console.log(object); var material = new THREE.MeshBasicMaterial( {color: 0xffffff, side: THREE.DoubleSide } ); scene.add( object ); object.traverse( function ( child ) { if ( child instanceof THREE.Mesh ) { child.material = material; child.updateMatrix(); // as needed child.updateMatrixWorld(); // as needed objects.push(child); } } ); setupRaycaster(); }); } /////////////////////////////////// RAYCASTER AND RED LINE VISUALISATION function setupRaycaster(){ var material = new THREE.LineBasicMaterial({color: 0xff0000}); var raylength=100; var count=90; var angle=360/count; for (var i=0; i<count; i++){ var x=0; var y=0; var z=0; var v1=new THREE.Vector3( x, y, z); var v2=new THREE.Vector3( x+raylength*Math.cos(i*angle*Math.PI/180), y+raylength*Math.sin(i*angle*Math.PI/180), z); var geometry = new THREE.Geometry(); geometry.vertices.push(v1); geometry.vertices.push(v2); var line = new THREE.Line( geometry, material ); scene.add( line ); var raycaster = new THREE.Raycaster(); raycaster.set ( v1, v2 ); var intersects = raycaster.intersectObjects( objects , true); console.log(i,intersects); if(intersects[0]){ cutOutPoints.push(intersects[0].point); } } console.log(cutOutPoints); /////////////////////////////////// YELLOW EXTRUDE GEOMETRY var cutOutShape = new THREE.Shape(); if(cutOutPoints.length){// wenn cutpoints in Array cutOutShape.moveTo(cutOutPoints[0].x, cutOutPoints[0].y); for (var i=1; i<cutOutPoints.length; i++){ cutOutShape.lineTo(cutOutPoints[i].x, cutOutPoints[i].y); } var cutOutMaterial = new THREE.LineBasicMaterial({color: 0xffcc00}); var extrudeSettings = { amount: 60, bevelEnabled: false}; var geometry = new THREE.ExtrudeGeometry( cutOutShape, extrudeSettings ); var cutOutMesh = new THREE.Mesh( geometry, cutOutMaterial ); scene.add( cutOutMesh ); } }
a while ago I tried to solve this original problem of cutting a sink out of a cupboard: Subtracting a 3D Sink from a 3D Cupboard-Board in ThreeJS
Unfortunately, other solutions yielded not the desired results, but using raycasting to trace the inside of the sink (and generate a new shape to function as a boolean) seems like a promising lead.
-
Unity - Aim Line (Line Renderer) not showing in 2D shooter
I'm a Unity novice and I'm creating a small 2D shooting game on a school project and I already managed to have a functional shooting system in the main character that even bounces off some objects using Unity Physics.
I now wanted to integrate an aim line that will predict the trajectory of the bullet, including the bounces on objects (bubble-shooter style).
I found a script that uses Raycast and Line Renderer and it supposedly does this and I tried to integrate it into my gun script but although it does not give any error, it simply does not show anything when I test the game. I do not know if the problem is in the settings that I put in the Line Renderer Component or it is in the Script.
Could someone help me understand where my error is and point the right way?
My goal is:
My Line Renderer Component Definitions:
My Weapon Script:
using System.Collections; using System.Collections.Generic; using UnityEngine; [RequireComponent(typeof(LineRenderer))] public class Weapon : MonoBehaviour { [Range(1, 5)] [SerializeField] private int _maxIterations = 3; [SerializeField] private float _maxDistance = 10f; public int _count; public LineRenderer _line; public Transform Firepoint; public GameObject BulletPrefab; public GameObject FirePrefab; void Start() { _line = GetComponent<LineRenderer>(); } // Update is called once per frame void Update() { if (Input.GetButtonDown("Fire1")) { Shoot(); } _count = 0; _line.SetVertexCount(1); _line.SetPosition(0, transform.position); _line.enabled = RayCast(new Ray(transform.position, transform.forward)); } void Shoot() { //shooting logic var destroyBullet = Instantiate(BulletPrefab, Firepoint.position, Firepoint.rotation); Destroy(destroyBullet, 10f); var destroyFire = Instantiate(FirePrefab, Firepoint.position, Firepoint.rotation); Destroy(destroyFire, 0.3f); } private bool RayCast(Ray ray) { RaycastHit hit; if (Physics.Raycast(ray, out hit, _maxDistance) && _count <= _maxIterations - 1) { _count++; var reflectAngle = Vector3.Reflect(ray.direction, hit.normal); _line.SetVertexCount(_count + 1); _line.SetPosition(_count, hit.point); RayCast(new Ray(hit.point, reflectAngle)); return true; } _line.SetVertexCount(_count + 2); _line.SetPosition(_count + 1, ray.GetPoint(_maxDistance)); return false; } }
-
Angular subscription only triggers from 1 component
I have an toast service to use in the whole application. But only I can make it work only from one component which it is the top navigation bar. But when i try to trigger it from others component doesn't work.
//Toast Service
@Injectable() export class NotifyService { private subject = new BehaviorSubject<Notify>(null); subscribe = this.subject.asObservable(); private keepAfterNavigation = false; constructor(private router: Router) { // clear notify messages on route change unless 'keepAfterNavigation' flag is true router.events.subscribe(event => { if (event instanceof NavigationStart) this.keepAfterNavigation ? this.keepAfterNavigation = false : this.clear(); }); } getNotify(): Observable<any> { return this.subject.asObservable(); } success(message: string, pos: string, keepAfterNavigation = false) { this.notify(NotifyType.Success, message, pos, keepAfterNavigation); } error(message: string, pos: string, keepAfterNavigation = false) { this.notify(NotifyType.Error, message, pos, keepAfterNavigation); } info(message: string, pos: string, keepAfterNavigation = false) { this.notify(NotifyType.Info, message, pos, keepAfterNavigation); } warn(message: string, pos: string, keepAfterNavigation = false) { this.notify(NotifyType.Warning, message, pos, keepAfterNavigation); } notify(type: NotifyType, message: string, pos: string, keepAfterNavigation = false) { this.keepAfterNavigation = keepAfterNavigation; this.subject.next(<Notify>{ type: type, message: message, position: pos }); } clear() { this.subject.next(null); } }
//Toast Component
export class NotifyComponent implements OnInit { ngOnInit() { this.notifyService.getNotify().subscribe((notify: Notify) => { if (!notify) { // clear notifies when an empty notify is received this.notifies = []; return; } // add notify to array this.notifies.push(notify); }); } }
Maybe is something related to this (not sure at all):
//App component
<notify></notify> <header> <main-nav></main-nav> </header> <side-bar></side-bar> <main id="main-content"> <router-outlet></router-outlet> </main>
As you can see the main-nav is fixed (Only component that triggers) meanwhile the others components depend on router (router-outlet).
Thanks in advance.
-
Observables in nestjs - Reading a file asynchronously
I am trying a use case of reading a json file asynchronously and sending it out as a response (as a rxjs observable data). Here is the service that I use
import { logger } from './../../shared/utils/logger'; import { Injectable } from '@nestjs/common'; import * as fs from 'fs'; import * as path from 'path'; import { BehaviorSubject, Observable, pipe, of, from, throwError, merge} from 'rxjs'; import { map, filter, scan, take, debounce, switchMap, retry, catchError, mergeMap, delay, zip, tap, mapTo } from 'rxjs/operators'; import { HttpResponseModel } from '../model/config.model'; import { isNullOrUndefined } from 'util'; @Injectable() export class NewProviderService { serviceSubject: BehaviorSubject<HttpResponseModel[]>; filePath: string; httpResponseObjectArray: HttpResponseModel[]; constructor() { this.serviceSubject = new BehaviorSubject<HttpResponseModel[]>([]); this.filePath = path.resolve(__dirname, './../../shared/assets/httpTest.json'); this.setSubject(); } readFileFromJSON() { this.readFileFromJsonSync(); fs.exists(this.filePath.toString(), exists => { if (exists) { fs.readFile(this.filePath.toString(), 'utf-8', (err, data) => { logger.info('file read without parsin', data); this.httpResponseObjectArray = JSON.parse(data).HttpTestResponse; logger.info('array obj is:', this.httpResponseObjectArray); logger.info('file read after parsing', JSON.parse(data)); return this.httpResponseObjectArray; }); } else { return null; } }); } getObservable(): Observable<HttpResponseModel[]> { // create an observable // return Observable.create(observer => { // observer.next(this.readFileFromJSON()); // }); return of(this.readFileFromJsonSync()).pipe(map(data => { logger.info('inside obs methid', data); return data; })); } setSubject() { this.getObservable().subscribe(data => { logger.info('data before setting in sub', data); this.serviceSubject.next(data); }); } }
So I wanted to subscribe to this emitted observable in the controller, but the values are getting read after I have subscribed and read the subject (
BehaviorSubject
). I understand that I am kind of doing something wrong with the subscription and emitting of data, but couldn't understand where I am doing wrong. Every time the controller prints 'data subscribed undefined' and then continues to read the file and emit the observableThis is the controller data
@Get('/getJsonData') public async getJsonData(@Req() requestAnimationFrame, @Res() res) { this.newService.serviceSubject.subscribe(data => { logger.info('data subscribed', data); res.status(HttpStatus.OK).send(data); }); }
It works well if I read the file synchronously
replace
readFileFromJSON()
with the following method and it works wellreadFileFromJsonSync(): HttpResponseModel[] { const objRead = JSON.parse(fs.readFileSync(this.filePath.toString(), {encoding: 'utf-8'})); logger.info('object read is', objRead.HttpTestResponse); return objRead.HttpTestResponse; }
So I am missing something while reading the file async. I am not sure what am I doing wrong. Could someone please help?
-
Pass BehaviorSubject value as parameter
I have an Angular component with a BehaviourSubject initialized to the current month:
textLabel: string; private monthIndex$: BehaviorSubject<number>; private MONTHS = [ "Gennaio", "Febbraio", "Marzo", "Aprile", "Maggio", "Giugno", "Luglio", "Agosto", "Settembre", "Ottobre", "Novembre", "Dicembre" ]; constructor(private listService: ShoppingListService) {} ngOnInit() { this.monthIndex$ = new BehaviorSubject<number>(new Date().getMonth()); // Like this it does not display the label this.setMonthLabel(this.monthIndex$.value); this.model$ = this.monthIndex$.pipe( switchMap((monthValue: number) => { // this.setMonthLabel(monthValue); // This way it works! return this.listService.getHistoryChartModel(monthValue); }), takeUntil(this.destroy$) ); } private setMonthLabel(monthIndex: number) { this.textLabel = this.MONTHS[monthIndex]; } setMonth(direction: number) { let monthIndex = this.monthIndex$.getValue(); monthIndex += direction; monthIndex = monthIndex < 0 ? 0 : monthIndex > 11 ? 11 : monthIndex; this.monthIndex$.next(monthIndex); this.setMonthLabel(monthIndex); }
And the template:
<div class="view-sel-container"> <button color="primary" mat-icon-button (click)="setMonth(-1)" [disabled]="monthIndex === 0"> <i class="material-icons"> keyboard_arrow_left </i> </button> <span class="label-text" *ngIf="textLabel">{{ textLabel }}</span> <button color="primary" mat-icon-button (click)="setMonth(1)" [disabled]="monthIndex === 11"> <i class="material-icons"> keyboard_arrow_right </i> </button>
Is it a timing reason why by passing the BehavourSubject value to the method
this.setMonthLabel(this.monthIndex$.value)
, the label is not displayed in the template?UPDATE
The solution provided by Deborah Kurata using get/set instead of BehaviourSubject is the best way to go. I leave the original question/code open as I still do not get why the code does now work by passing the behaviourSubject value as parameter.